Sum of elements stored inside a tuple

后端 未结 5 683
小蘑菇
小蘑菇 2021-01-12 03:48

Given a tuple containing a bunch of integer elements, how can one find the sum of all the elements?

For example, if I have a list of tuples:

li = [(1         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 04:00

    Both solutions below will work.

    li = [(1, 2), (1, 3), (2, 3)]
    print([sum(i) for i in li])
    

    or

    def sumtupleinlist(lst):
        return [sum(i) for i in lst]
    li = [(1, 2), (1, 3), (2, 3)]
    

    To test the function, run :

    print(sumtupleinlist(li))
    

提交回复
热议问题