我想减去两个列表中的值。
a = [1,2,3,4]
b = [1,0,1,5]
c = a - b
#c should be = [0,2,2,-1]
How can I add the corresponding elements of several lists of numbers?的答案是类似的,但很多答案只适用于添加。
如果可能,请回答如何减去。
答案 0 :(得分:2)
c = [a1 - b1 for (a1, b1) in zip(a, b)]
答案 1 :(得分:2)
在你的情况下,itertools.starmap
可能会有用:
>>> a = [1,2,3,4]
>>> b = [1,0,1,5]
>>>
>>> import itertools as it
>>>
>>> import operator as op
>>>
>>> list(it.starmap(op.sub, zip(a,b)))
[0, 2, 2, -1]
OR:
>>> [item for item in it.starmap(op.sub, zip(a,b))]
[0, 2, 2, -1]
答案 2 :(得分:0)
大多数人使用numpy
进行数值运算(虽然p.magalhaes的答案是"纯" python)。
import numpy as np
a=np.array([1,2,3,4])
b=np.array([1,0,1,5])
c = a - b
c
返回
array([ 0, 2, 2, -1])