如何在python中总结一个列表 [英] How to sum a list in python

查看:42
本文介绍了如何在python中总结一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

   print sum(arr)

如果我输入字符串1,2,3,4",第一行将它拆分为一个由 1,2,3,4 组成的列表.但是当我打印总和时,它不起作用,我收到一条错误消息.

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.

推荐答案

在您的情况下,您拆分字符串但结果不会再次分配给 arr 因此您的变量 arr value 没有改变它仍然是字符串,所以当你应用 sum(arr) 时,它给出了一个错误.但是如果你把它分配给 arr ,拆分元素的类型是 所以把它转换成 integer

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

我尝试在 Python 3 中使用 split 而不是 rsplit 解决方案:

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

输出:10

它将每个元素转换为整数,然后求和.但是,如果您尝试在 map 方法之后打印 arr : print(arr) 它会给出输出: 所以转换 arrlist 来访问元素 所以代替 arr = map(int,arr.split(','))arr = list(map(int,arr.split(',')))

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(',')))

如果你想使用 rsplit 那么解决方案(在 python 3 中):

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

这篇关于如何在python中总结一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆