[英]How do I sum the first value in each tuple in a list of tuples in 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, ie:我想找到每对中第一项的总和,即:
0 + 2 + 5 + 2
How can I do this in Python?我怎样才能在 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.我有一种感觉,必须有一种更 Pythonic 的方式。
A version compatible with Python 2.3 is与 Python 2.3 兼容的版本是
sum([pair[0] for pair in list_of_pairs])
or in recent versions of Python, see this answer or this one .或在 Python 的最新版本中,请参阅此答案或此答案。
sum(i for i, j in list_of_pairs)
也会做。
I recommend:我建议:
sum(i for i, _ in list_of_pairs)
Note :注意:
Using the variable _
(or __
to avoid confliction with the alias of gettext
) instead of j
has at least two benefits:使用变量_
(或__
以避免与gettext
的别名冲突)而不是j
至少有两个好处:
_
(which stands for placeholder) has better readability _
(代表占位符)具有更好的可读性pylint
won't complain: "Unused variable 'j'" pylint
不会抱怨:“未使用的变量‘j’”If you have a very large list or a generator that produces a large number of pairs you might want to use a generator based approach.如果您有一个非常大的列表或生成大量对的生成器,您可能需要使用基于生成器的方法。 For fun I use itemgetter()
and imap()
, too.为了好玩,我也使用itemgetter()
和imap()
。 A simple generator based approach might be enough, though.不过,一个简单的基于生成器的方法可能就足够了。
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))
Note that itertools.imap()
is available in Python >= 2.3.请注意itertools.imap()
在 Python >= 2.3 中可用。 So you can use a generator based approach there, too.所以你也可以在那里使用基于生成器的方法。
Obscure (but fun) answer:晦涩(但有趣)的答案:
>>> sum(zip(*list_of_pairs)[0])
9
Or when zip's are iterables only this should work:或者当 zip 是可迭代的时,只有这应该工作:
>>> sum(zip(*list_of_pairs).__next__())
9
Below is sample code, you can also specify the list range.下面是示例代码,您还可以指定列表范围。
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
如果你不介意将其转换为numpy的数组,你可以使用np.sum
在axis=0
给出这里
s,p=0,0
for i in l:
s=s+i[0]
p=p+i[1]
print(tuple(s,p))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.