Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python:一个常量减去列表中的元素以返回一个列表_Python 3.x_List_Element - Fatal编程技术网

Python 3.x Python:一个常量减去列表中的元素以返回一个列表

Python 3.x Python:一个常量减去列表中的元素以返回一个列表,python-3.x,list,element,Python 3.x,List,Element,我有一个列表decation\u positions=[0.2,3,0.5,5,1,7,1.5,8],我想要这样一个列表 new_position = 2 - decay_positions 基本上我想要一个新的列表,其中元素等于2减去decation\u位置的元素 然而,当我这样做时: decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8] print(2 - decay_positions) 我明白了 所以我想如果维度不一样,你可以减去。所以我做

我有一个列表
decation\u positions=[0.2,3,0.5,5,1,7,1.5,8]
,我想要这样一个列表

new_position = 2 - decay_positions
基本上我想要一个新的列表,其中元素等于2减去
decation\u位置的元素
然而,当我这样做时:

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

所以我想如果维度不一样,你可以减去。所以我做了

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
print([2]*len(decay_positions) - decay_positions)
但它仍然给出了
TypeError:-:'int'和'list'的不支持的操作数类型

尽管
[2]*len(衰变位置)
衰变位置
大小相同。那么你的想法呢?元素相减不是很简单吗?

使用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)
试一试


所以我所要做的就是使用numpy
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 ]