[英]Sum the second value of each tuple in a list
I have structure like this: 我有这样的结构:
structure = [('a', 1), ('b', 3), ('c', 2)]
I would like to sum the integers ( 1+3+2
) using sum()
builtin method (in one line). 我想使用
sum()
内置方法(在一行中)对整数( 1+3+2
) sum()
。
Any ideas? 有任何想法吗?
sum(n for _, n in structure)
会工作。
sum(x[1] for x in structure)
应该管用
你可以做
sum(zip(*structure)[1])
使用功能样式,您可以
reduce(lambda x,y:x+y[1], structure,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.