How to sum a list of numbers stored as strings

后端 未结 2 1920
鱼传尺愫
鱼传尺愫 2021-01-17 05:50

Having a list of numbers stored as strings how do I find their sum?

This is what I\'m trying right now:

numbers = [\'1\', \'3\', \'7\']
result = sum(in         


        
相关标签:
2条回答
  • 2021-01-17 06:32

    If you prefer a less functional style, you can use a generator expression

    result = sum(int(x) for x in numbers))
    
    0 讨论(0)
  • 2021-01-17 06:36

    int(numbers) is trying to convert the list to an integer, which obviously won't work. And if you had somehow been able to convert the list to an integer, sum(int(numbers)) would then try to get the sum of that integer, which doesn't make sense either; you sum a collection of numbers, not a single one.

    Instead, use the function map:

    result = sum(map(int, numbers))
    

    That'll take each item in the list, convert it to an integer and sum the results.

    0 讨论(0)
提交回复
热议问题