使用lambda函数在嵌套列表中求和
我有一个数据结构,类似于这个
table = [
("marley", "5"),
("bob", "99"),
("another name", "3")
]
我想做的是,像这样计算第二列的总和(5 + 99 + 3):
total = sum(table, lambda tup : int(tup[1]))
这和Python中的sorted
函数的语法有点像,但这并不是你使用Python的sum
函数的方式。
那么,用Python的“优雅”或“函数式”的方式来计算第二列的总和应该怎么做呢?
6 个回答
2
你也可以访问字典中的值:
total = sum(map(int, dict(table).values())
这可能有点难懂。
3
sum(map(int,zip(*table)[-1]))
这是一种做法……不过还有很多其他选择。
12
如果你想使用lambda,下面的代码应该能解决你的问题:
total = sum(map(lambda x: int(x[1]), table))
14
reduce可以帮忙
from functools import reduce
total = reduce(lambda accumulator,element:accumulator+int(element[1]), table,0)
62
一种方法是使用 生成器表达式:
total = sum(int(v) for name,v in table)