如何在python中以数学方式减去两个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23173294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:24:15  来源:igfitidea点击:

How to mathematically subtract two lists in python?

pythonlistsubtraction

提问by Gareth Bale

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?

我知道 python 不支持列表的减法,但是有一些方法可以省略两个列表之间的公共元素。但是我想要做的是将一个列表中的每个元素分别与另一个列表中的相应元素相减,并将结果作为输出列表返回。我怎样才能做到这一点?

     A = [3, 4, 6, 7]
     B = [1, 3, 6, 3]
     print A - B  #Should print [2, 1, 0, 4]

采纳答案by Thanakron Tandavas

Use operatorwith mapmodule:

运算符地图模块一起使用:

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> map(operator.sub, A, B)
[2, 1, 0, 4]

As @SethMMortonmentioned below, in Python 3, you need this instead

正如下面提到的@SethMMorton,在 Python 3 中,你需要这个

>>> A = [3, 4, 6, 7]
>>> B = [1, 3, 6, 3]
>>> list(map(operator.sub, A, B))
[2, 1, 0, 4]

Because, mapin Python returns an iterator instead.

因为,Python 中的map返回一个迭代器。

回答by Gareth Bale

You can use zipand a list comprehension:

您可以使用zip列表理解

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

回答by Lucas S.

Try something like

尝试类似的东西

def substract_lists(a, b):
    for i, val in enumerate(a):
            val = val - b[i]
    return a