我想減去兩個列表中的值。如何從一個集合中減去另一個集合中的數字?
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?是simular,但很多它的答案只適用於加入。
如果可能,請回答如何減去。
我想減去兩個列表中的值。如何從一個集合中減去另一個集合中的數字?
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?是simular,但很多它的答案只適用於加入。
如果可能,請回答如何減去。
大概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]
c = [a1 - b1 for (a1, b1) in zip(a, b)]
大多數人使用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])
你的意思'list','set's在Python無序。 – AChampion
可能重複[如何添加幾個數字列表的相應元素?](http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-名單-的號碼)。它不完全一樣,但它足夠接近,可以作爲一個愚蠢的關閉。 – zondo
如果你的大部分代碼都是這樣的,你應該嘗試R.用'a'和'b'作爲向量,'c <-a-b'已經可以做你想要的了。 – TigerhawkT3