Python 使用 lambda 函数在嵌套列表中查找总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25047561/
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-18 19:38:43  来源:igfitidea点击:

Finding a sum in nested list using a lambda function

pythonlambdafunctional-programmingsum

提问by hlin117

I have a data structure similar to this

我有一个与此类似的数据结构

table = [
    ("marley", "5"),
    ("bob", "99"),
    ("another name", "3")
]

What I would like to do, to get the sum of the 2nd column (5 + 99 + 3) functionally like this:

我想要做什么,在功能上像这样获得第二列 (5 + 99 + 3) 的总和:

total = sum(table, lambda tup : int(tup[1]))

That would be similar syntax to the python function sorted, but that's not how you would use python's sumfunction.

这与 python function 的语法相似sorted,但这不是您使用 pythonsum函数的方式。

What's the pythonic/functional way to sum up the second column?

总结第二列的 pythonic/function 方法是什么?

采纳答案by Peter de Rivaz

One approach is to use a generator expression:

一种方法是使用生成器表达式

total = sum(int(v) for name,v in table)

回答by Joran Beasley

sum(map(int,zip(*table)[-1]))

is one way to do it ... there are many options however

是一种方法......但是有很多选择

回答by rth

reduce can help

减少可以帮助

total = reduce(lambda x,y:x+int(y[1]), table,0)

回答by FredrikHedman

If you want to use lambda the following should solve it:

如果你想使用 lambda,以下应该解决它:

total = sum(map(lambda x: int(x[1]), table))

回答by Peter Wood

You can also get at the values in a dictionary:

您还可以获取字典中的值:

total = sum(map(int, dict(table).values())

This may be a little obscure.

这可能有点晦涩。

回答by SRG

One way is using indexing.

一种方法是使用索引。

total=sum(items[1] for items in table)