简体   繁体   English

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

[英]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至少有两个好处:

  1. _ (which stands for placeholder) has better readability _ (代表占位符)具有更好的可读性
  2. 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.sumaxis=0给出这里

                s,p=0,0
                for i in l:
                  s=s+i[0]
                  p=p+i[1]
               print(tuple(s,p))
  1. enter code here在此处输入代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中的元组列表中对每个元组中的前两个值求和? - How do I sum the first two values in each tuple in a list of tuples in Python? 如何在python中修改每个列表/元组中的第一个值? - How do I modify the first value in each list / tuple in python? 如何根据每个元组中第一个数字的值从元组列表中弹出项目? - How do I pop item off a list of tuples, based on the value of the first number in each tuple? 如何使用每个元组的第一个值作为键将六个元组列表连接到 Pandas 数据框中? - How do I join six list of tuples into a pandas dataframe using the first value of each tuple as the key? 如何对第一个值相同的列表中的元组求和? - How do I sum tuples in a list where the first value is the same? Python list_of_tuples:每个元组的第二个val,仅当元组的第一个val == - Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something 如何将元组列表转换为 Pandas 数据框,以便每个元组的第一个值代表一列? - How can I transform a list of tuples into a pandas dataframe so that the first value of each tuple represents a column? 给定一个元组列表,如果第一个元素相同,我如何在每个相似的元组中添加第二个元素 - Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple 如何用元组中每个元组的第一个值构成一个新元组? - How to form a new tuple with the first value of each tuple of a tuple of tuples? 如何基于第一个值Python替换元组排序列表中的元组 - How to replace a tuple in sorted list of tuples basing on first value Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM