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

后端 未结 8 710
时光取名叫无心
时光取名叫无心 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:42
    sum(i for i, j in list_of_pairs)
    

    will do too.

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

    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:

    1. _(which stands for placeholder) has better readability
    2. pylint won't complain: "Unused variable 'j'"
    0 讨论(0)
提交回复
热议问题