Sum of elements stored inside a tuple

后端 未结 5 682
小蘑菇
小蘑菇 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:23

    For beginner:

    1. Create result variable which type is list.
    2. Iterate every item from the give list by for loop.
    3. As every item is tuple so again iterate item from the step 2 and set sum of item to 0.
    4. Add sum.
    5. Append sum to result variable.

    Demo:

    >>> li = [(1, 2), (1, 3), (2, 3)]   # Given Input
    >>> result = []                     # Step 1
    >>> for i in li:                    # Step 2
    ...     tmp_sum = 0                 # Step 3  
    ...     for j in i:                 # Step 3
    ...         tmp_sum += j            # Step 4 
    ...     result.append(tmp_sum)      # Step 5 
    ... 
    >>> print result
    [3, 4, 5]
    

提交回复
热议问题