How do I sum the first value in each tuple in a list of tuples in Python?

后端 未结 8 709
时光取名叫无心
时光取名叫无心 2020-12-05 10:03

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 pai

相关标签:
8条回答
  • 2020-12-05 10:32

    A version compatible with Python 2.3 is

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

    or in recent versions of Python, see this answer or this one.

    0 讨论(0)
  • 2020-12-05 10:33

    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. 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. So you can use a generator based approach there, too.

    0 讨论(0)
  • 2020-12-05 10:33

    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
    
    0 讨论(0)
  • 2020-12-05 10:34

    Obscure (but fun) answer:

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

    Or when zip's are iterables only this should work:

    >>> sum(zip(*list_of_pairs).__next__())
    9
    
    0 讨论(0)
  • 2020-12-05 10:34

    If you don't mind converting it to a numpy array, you can use np.sum over axis=0 as given here

    0 讨论(0)
  • 2020-12-05 10:40
                    s,p=0,0
                    for i in l:
                      s=s+i[0]
                      p=p+i[1]
                   print(tuple(s,p))
    
    1. enter code here

    0 讨论(0)
提交回复
热议问题