2013-07-01 100 views

回答

4

如何合併基於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內存高效的解決方案,因爲它返回一個迭代器。

7

列表理解。

[x - y for (x, y) in zip(a, b)] 
1

您可以使用zip與列表理解:

>> [x-y for (x, y) in zip(a, b)] 
5
from operator import sub 

a=[1,2,3,4] 
b=[2,1,3,2] 

print map(sub, a, b) 
# [-1, 1, 0, 2] 
相關問題