How to subtract two lists in python [duplicate]

冷暖自知 提交于 2019-11-29 13:13:05

Try this:

[x1 - x2 for (x1, x2) in zip(List1, List2)]

This uses zip, list comprehensions, and destructuring.

This solution uses numpy. It makes sense only for largish lists as there is some overhead in instantiate the numpy arrays. OTOH, for anything but short lists, this will be blazingly fast.

>>> import numpy as np
>>> a = [3,5,6]
>>> b = [3,7,2]
>>> list(np.array(a) - np.array(b))
[0, -2, 4]

You can use list comprehension, as @Matt suggested. you can also use itertools - more specifically, the imap() function:

>>> 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

Like all itertools funcitons, imap() returns an iterator. You can generate a list passing it as a parameter for the list() constructor:

>>> list(imap(int.__sub__, a, b))
[0, -2, 4]
>>> list(imap(lambda m, n: m-n, a, b)) # Using lambda
[0, -2, 4]

EDIT: As suggested by @Cat below, it would be better to use the operator.sub() function with imap():

>>> from operator import sub
>>> list(imap(sub, a, b))
[0, -2, 4]

Yet another solution below:

>>> 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]

ADDITION: Just check for the python reference of map and you'll see you could pass more than one iterable to map

Anjaneyulu Batta

You can do it in the following way

List1 = [3,5,6]
List2 = [3,7,2]
ans = [List1[i]-List2[i] for i in xrange(min(len(List1), len(List2)))]
print ans

that outputs [0, -2, 4]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!