将数字字符串转换为整数列表. Python [英] Convert a string of numbers to a list of integers. Python
问题描述
我正在尝试将字符串str1转换为数字列表,以便可以对其进行汇总.首先,我使用split()函数理解str1中的数字,然后将字符串转换为列表(lista),然后使用map()函数将新列表中的字符串转换为整数:
I am trying to convert the string str1 to a list of numbers so that I could sum them up. First I use the split() function to make sense of the numbers in str1, I cast the string into a list (lista) and after that I use the map() function in order to convert the strings in the new list to integers:
str1="13,22,32,4,5"
str2=str1.split()
lista=list(str2)
lista=map(int,lista)
print sum(lista)
由于某种原因,我收到以下错误消息:"ValueError:以10为底的int()的无效文字:'13,22,32,4,5'"
For some reason I get the following error message: "ValueError: invalid literal for int() with base 10: '13,22,32,4,5'"
推荐答案
使用split()
不会拆分str1
,因为如果没有sep
参数,则默认分隔符为空格' '
.因此:
Using split()
will not split up str1
, as without the sep
argument the default separator is a space ' '
. Hence:
str2 == ["13,22,32,4,5"]
您需要指定split
应该使用逗号','
.实际上,您可以将您的操作合并为一个:
you need to specify that split
should use a comma ','
. In fact, you can combine your operations into one:
sum(map(int, str1.split(',')))
这篇关于将数字字符串转换为整数列表. Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!