Python:一个常量减去一个列表的元素到return一个列表

Python: A constant subtract by elements of a list to return a list

我有一个列表 decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8] 我想要一个这样的列表

new_position = 2 - decay_positions

本质上我想要一个新列表,其中的元素等于 2 减去 decay_positions 的元素 但是当我这样做时:

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
print(2 - decay_positions)

我明白了

TypeError: unsupported operand type(s) for -: 'int' and 'list'

所以我想也许如果尺寸不一样你可以减去。所以我做了

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
print([2]*len(decay_positions) - decay_positions)

但它仍然给出 TypeError: unsupported operand type(s) for -: 'int' and 'list'

尽管 [2]*len(decay_positions)decay_positions 具有相同的大小。那么想法?元素减法不应该非常简单吗?

使用 numpy ftw:

>>> import numpy as np
>>> decay_positions = np.array([0.2, 3, 0.5, 5, 1, 7, 1.5, 8])
>>> 2 - decay_positions
array([ 1.8, -1. ,  1.5, -3. ,  1. , -5. ,  0.5, -6. ])

如果你出于某种原因鄙视 numpy,你总是可以使用列表理解作为次要选项:

>>> [2-dp for dp in [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]]
[1.8, -1, 1.5, -3, 1, -5, 0.5, -6]

你可以这样做:

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
result = [2-t for t in decay_positions]
print(result)

尝试

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
new_decay_positions = [2-pos for pos in decay_positions ]

我只想补充一点,如果您想就地修改列表,您可以这样做

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
decay_positions[:] = (2 - it for it in decay_positions)
print(decay_positions)