我有兩個大小相等的名單,我想做出第三個將包含每個前兩個的區別:如何合併基於python中的函數的兩個列表?
a=[1,2,3,4]
b=[2,1,3,2]
,我想計算c=[a[0]-b[0],a[1]-b[1],a[2]-b[2],a[3]-b[3],]
是否有一個Python的方式?
我有兩個大小相等的名單,我想做出第三個將包含每個前兩個的區別:如何合併基於python中的函數的兩個列表?
a=[1,2,3,4]
b=[2,1,3,2]
,我想計算c=[a[0]-b[0],a[1]-b[1],a[2]-b[2],a[3]-b[3],]
是否有一個Python的方式?
如何合併基於python中的函數的兩個列表?
您正在尋找zip
和列表理解:
>>> a=[1,2,3,4]
>>> b=[2,1,3,2]
>>> def func(x,y):
... return x-y
>>> c = [func(x,y) for x,y in zip(a,b)]
>>> c
[-1, 1, 0, 2]
幫助上zip
:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
使用itertools.izip
內存高效的解決方案,因爲它返回一個迭代器。
列表理解。
[x - y for (x, y) in zip(a, b)]
您可以使用zip
與列表理解:
>> [x-y for (x, y) in zip(a, b)]
from operator import sub
a=[1,2,3,4]
b=[2,1,3,2]
print map(sub, a, b)
# [-1, 1, 0, 2]