我无法想出如何在Python中编写一个可以计算这个的函数:
List1=[3,5,6]
List2=[3,7,2]
结果应该是一个新列表,从List1中减去List2,List3=[0,-2,4]
!我知道,我不知道该怎么做,但我必须使用zip函数。通过这样做,我得到:([(3, 3),(5, 7),(6, 2)])
,但我现在不知道该怎么做?
我无法想出如何在Python中编写一个可以计算这个的函数:
List1=[3,5,6]
List2=[3,7,2]
结果应该是一个新列表,从List1中减去List2,List3=[0,-2,4]
!我知道,我不知道该怎么做,但我必须使用zip函数。通过这样做,我得到:([(3, 3),(5, 7),(6, 2)])
,但我现在不知道该怎么做?
试试这个:
[x1 - x2 for (x1, x2) in zip(List1, List2)]
这段代码使用了 zip
、列表推导式和解构。
这个解决方案使用NumPy库。它只对较大的列表有效,因为实例化NumPy数组存在一些开销。然而,对于任何非短列表,它将运行得非常快。
>>> import numpy as np
>>> a = [3,5,6]
>>> b = [3,7,2]
>>> list(np.array(a) - np.array(b))
[0, -2, 4]
imap()
函数:>>> from itertools import imap
>>> from operator import sub
>>> a = [3,5,6]
>>> b = [3,7,2]
>>> imap(int.__sub__, a, b)
<itertools.imap object at 0x50e1b0>
>>> for i in imap(int.__sub__, a, b):
... print i
...
0
-2
4
像所有的itertools函数一样,imap()
会返回一个迭代器。你可以通过将其作为参数传递给list()
构造函数来生成一个列表:
>>> list(imap(int.__sub__, a, b))
[0, -2, 4]
>>> list(imap(lambda m, n: m-n, a, b)) # Using lambda
[0, -2, 4]
编辑:如@Cat下面建议的那样,最好使用imap()
函数与operator.sub()
一起使用:
>>> from operator import sub
>>> list(imap(sub, a, b))
[0, -2, 4]
operator.sub
比int.__sub__
更通用,并且下划线更少。 - Cat Plus Plus>>> a = [3,5,6]
>>> b = [3,7,2]
>>> list(map(int.__sub__, a, b)) # for python3.x
[0, -2, 4]
>>> map(int.__sub__, a, b) # and for python2.x
[0, -2, 4]
补充:只需查看Python中map
的参考文献,您就会发现可以将多个可迭代对象传递给map
map()
可以接受多个可迭代对象,这太好了! - brandizziList1 = [3,5,6]
List2 = [3,7,2]
ans = [List1[i]-List2[i] for i in range(min(len(List1), len(List2)))]
print ans
输出 [0, -2, 4]
的代码
xrange
仅适用于 Python 2,在 Python 3 中,range
执行相同的操作。 - kristianp