问题
I know subtraction of lists is not supported in python, however there are some ways to omit the common elements between two lists. But what I want to do is subtraction of each element in one list individually with the corresponding element in another list and return the result as an output list. How can I do this?
A = [3, 4, 6, 7]
B = [1, 3, 6, 3]
print A - B #Should print [2, 1, 0, 4]
回答1:
Use operator with map module:
>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> map(operator.sub, A, B)
[2, 1, 0, 4]
As @SethMMorton mentioned below, in Python 3, you need this instead
>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> list(map(operator.sub, A, B))
[2, 1, 0, 4]
Because, map in Python returns an iterator instead.
回答2:
You can use zip and a list comprehension:
>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> zip(A, B) # Just to demonstrate
[(3, 1), (4, 3), (6, 6), (7, 3)]
>>> [x - y for x, y in zip(A, B)]
[2, 1, 0, 4]
>>>
回答3:
Try something like
def substract_lists(a, b):
for i, val in enumerate(a):
val = val - b[i]
return a
来源:https://stackoverflow.com/questions/23173294/how-to-mathematically-subtract-two-lists-in-python