如何在Python中的元组列表中对每个元组的第一个值求和? [英] How do I sum the first value in each tuple in a list of tuples in Python?
本文介绍了如何在Python中的元组列表中对每个元组的第一个值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的元组列表(总是成对出现):
I have a list of tuples (always pairs) like this:
[(0, 1), (2, 3), (5, 7), (2, 1)]
我想找到每对中第一项的总和,即:
I'd like to find the sum of the first items in each pair, i.e.:
0 + 2 + 5 + 2
如何在Python中执行此操作?目前,我正在遍历列表:
How can I do this in Python? At the moment I'm iterating through the list:
sum = 0
for pair in list_of_pairs:
sum += pair[0]
我觉得必须有一种更Python化的方式.
I have a feeling there must be a more Pythonic way.
推荐答案
与Python 2.3兼容的版本是
A version compatible with Python 2.3 is
sum([pair[0] for pair in list_of_pairs])
或在最新版本的Python中,请参见此答案或
or in recent versions of Python, see this answer or this one.
这篇关于如何在Python中的元组列表中对每个元组的第一个值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文