Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to sum a list in python

arr.rsplit(',', len(arr))

   print sum(arr)

If I input the string of "1,2,3,4", the first line splits it in a list of 1,2,3,4. But when I print the sum it does not work I get an error message.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In your case your splitting the string but the result is not assigned again to arr so your variable arr value is not getting changed it remains the string, so while you apply sum(arr) it is giving an error. But if you assign it to arr the type of split elements is <class 'str'> so convert it into integer

I trying to use split instead of rsplit Solution in Python 3 :

arr = "1,2,3,4"
arr = map(int,arr.split(','))
print(sum(arr))

Output : 10

It will convert each element to integer and then take the sum. But if you try to print arr : print(arr) after the map method it gives output : <map object at 0x7f90c081acc0> So convert arr to list to access the elements So instead of arr = map(int,arr.split(',')) give arr = list(map(int,arr.split(',')))

If you want to use rsplit then Solution (in python 3):

arr = "1,2,3,4"
arr = list(map(int,arr.rsplit(',', len(arr))))
print(sum(arr))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...