This question already has an answer here:
- Subtracting 2 lists in Python 12 answers
I can't figure out how to make a function in python that can calculate this:
List1=[3,5,6]
List2=[3,7,2]
and the result should be a new list that substracts List2 from List1, List3=[0,-2,4]!
I know, that I somehow have to use the zip-function. By doing that I get:
([(3,3), (5,7), (6,2)]), but I don't know what to do now?
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
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]
来源:https://stackoverflow.com/questions/8194156/how-to-subtract-two-lists-in-python