更新时间:2022-12-08 23:30:20
在 Python 的现代版本中,我建议 SilentGhost 发布的内容(为了清楚起见在此重复):
sum(i for i, j in list_of_pairs)
在此答案的早期版本中,我曾建议这样做,这是必要的,因为 SilentGhost 的版本在当时最新的 Python (2.3) 版本中不起作用:
sum([pair[0] for list_of_pairs])
现在那个版本的 Python 已经过时了,而且 SilentGhost 的代码适用于所有当前维护的 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
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]
I have a feeling there must be a more Pythonic way.
In modern versions of Python I'd suggest what SilentGhost posted (repeating here for clarity):
sum(i for i, j in list_of_pairs)
In an earlier version of this answer I had suggested this, which was necessary because SilentGhost's version didn't work in the version of Python (2.3) that was current at the time:
sum([pair[0] for pair in list_of_pairs])
Now that version of Python is beyond obsolete, and SilentGhost's code works in all currently-maintained versions of Python, so there's no longer any reason to recommend the version I had originally posted.