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

后端 未结 8 733
时光取名叫无心
时光取名叫无心 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: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.

提交回复
热议问题