简体   繁体   English

如何在 Python 3 中减去嵌套列表中的元素?

[英]How to subtract the elements in a nested list in Python 3?

I have a nested list(the sublists will only have 2 elements), like this:我有一个嵌套列表(子列表只有 2 个元素),如下所示:

list_1 = [[1,2],[3,2]]

I want to subtract the elements inside each nested list, like this should be the output:我想减去每个嵌套列表中的元素,就像这样应该是输出:

[-1,1]

To sum the numerals in the nested list, I only had to use:为了总结嵌套列表中的数字,我只需要使用:

list_1 = [[1,2],[3,2]]
store = []
for x in list_1:
    store.append(sum(x))

but in subtracting since I couldn't any function like 'sum' for subtracting on the internet, I tried create one like this:但是在减法中,因为我无法在互联网上使用任何像“sum”这样的函数进行减法,所以我尝试创建一个这样的函数:

list_1 = [[1,2],[3,2]]
store = []
def subtraction(z,l):
    total = z - l
    return total
for y in list_1:
    store.append(subtraction(y))

but it returned:但它返回:

TypeError: subtraction() missing 1 required positional argument: 'l'

How can I get over this error and also make my code work?我怎样才能克服这个错误并使我的代码工作?

You can use Extended Iterable Unpacking operator.您可以使用Extended Iterable Unpacking运算符。

list_1 = [[1,2],[3,2]]
store = []
def subtraction(z,l):
    total = z - l
    return total
for y in list_1:
    store.append(subtraction(*y))

Another way is to use list comprehension .另一种方法是使用list comprehension

list = [a-b for a, b in list]

您可以通过使用列表理解来实现这一点

store = [ l1-l2 for l1, l2 in list_1]

The way I would go about it is:我会采取的方式是:

list_1 = [[1,2],[3,2]]
store = []
for a, b in list_1:
    store.append(a - b)

You can use a combination of map and lambda :您可以结合使用maplambda

list(map(lambda x: x[0] - x[1], list_1))

Demo :演示

>>> list_1 = [[1,2],[3,2]]
>>> list(map(lambda x: x[0] - x[1], list_1))
[-1, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM