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

Categories

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

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

1 Answer

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...