How to mathematically subtract two lists in python? [duplicate]

半城伤御伤魂 提交于 2019-11-29 10:59:07

问题


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

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