如何在 Python 中对元组列表中每个元组的第一个值求和?

问题描述 投票:0回答:8

我有一个这样的元组列表(总是成对的):

[(0, 1), (2, 3), (5, 7), (2, 1)]

我想找到每对中第一项的总和,即:

0 + 2 + 5 + 2

如何在 Python 中执行此操作?目前我正在遍历列表:

sum = 0
for pair in list_of_pairs:
   sum += pair[0]

我觉得一定有一种更 Pythonic 的方式。

python list tuples
8个回答
80
投票

在现代版本的 Python 中,我建议SilentGhost 发布的内容(为清楚起见,在此处重复):

sum(i for i, j in list_of_pairs)

在这个答案的早期版本中,我曾提出过这个建议,这是必要的,因为 SilentGhost 的版本在当时最新的 Python (2.3) 版本中不起作用:

sum([pair[0] for pair in list_of_pairs])

现在那个版本的 Python 已经过时了,SilentGhost 的代码适用于所有当前维护的 Python 版本,所以不再有任何理由推荐我最初发布的版本。


47
投票
sum(i for i, j in list_of_pairs)

也会做。


24
投票

我推荐:

sum(i for i, _ in list_of_pairs)

注意

使用变量

_
(或
__
以避免与
gettext
的别名冲突)而不是
j
至少有两个好处:

  1. _
    (代表占位符)具有更好的可读性
  2. pylint
    不会抱怨:“Unused variable 'j'”

6
投票

如果您有一个非常大的列表或生成大量对的生成器,您可能需要使用基于生成器的方法。为了好玩,我也使用

itemgetter()
imap()
。不过,一个简单的基于生成器的方法可能就足够了。

import operator
import itertools

idx0 = operator.itemgetter(0)
list_of_pairs = [(0, 1), (2, 3), (5, 7), (2, 1)]
sum(itertools.imap(idx0, list_of_pairs))

请注意,

itertools.imap()
在 Python >= 2.3 中可用。所以你也可以在那里使用基于生成器的方法。


4
投票

晦涩(但有趣)答案:

>>> sum(zip(*list_of_pairs)[0])
9

或者当 zip 是可迭代的时,这应该有效:

>>> sum(zip(*list_of_pairs).__next__())
9

0
投票

下面是示例代码,您也可以指定列表范围

def test_lst_sum():
    lst = [1, 3, 5]
    print sum(lst)  # 9
    print sum(lst[1:])  # 8

    print sum(lst[5:])  # 0  out of range so return 0
    print sum(lst[5:-1])  # 0

    print sum(lst[1: -1])  # 3

    lst_tp = [('33', 1), ('88', 2), ('22', 3), ('44', 4)]
    print sum(x[1] for x in lst_tp[1:])  # 9

0
投票

如果您不介意将其转换为 numpy 数组,您可以使用

np.sum
而不是
axis=0
here


-2
投票
s,p=0,0
for i in l:
  s=s+i[0]
  p=p+i[1]
print(tuple(s,p))
© www.soinside.com 2019 - 2024. All rights reserved.