Summing elements in a list

前端 未结 7 790
我在风中等你
我在风中等你 2020-11-30 23:16

Here is my code, I need to sum an undefined number of elements in the list. How to do this?

l = raw_input()
l = l.split(\' \')
l.pop(0)

My

7条回答
  •  无人及你
    2020-12-01 00:10

    You can sum numbers in a list simply with the sum() built-in:

    sum(your_list)
    

    It will sum as many number items as you have. Example:

    my_list = range(10, 17)
    my_list
    [10, 11, 12, 13, 14, 15, 16]
    
    sum(my_list)
    91
    

    For your specific case:

    For your data convert the numbers into int first and then sum the numbers:

    data = ['5', '4', '9']
    
    sum(int(i) for i in data)
    18
    

    This will work for undefined number of elements in your list (as long as they are "numbers")

    Thanks for @senderle's comment re conversion in case the data is in string format.

提交回复
热议问题