Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

python - How to sum a list of numbers stored as strings

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(int(numbers))

but this gives me an error:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    result = sum(int(numbers))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

I understand that I cannot force the list to be a number, but I can't think of a fix.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...