【问题标题】:Convert a string of numbers to a list of integers. Python将一串数字转换为整数列表。 Python
【发布时间】:2014-01-28 09:18:30
【问题描述】:

我正在尝试将字符串 str1 转换为数字列表,以便我可以总结它们。首先,我使用 split() 函数来理解 str1 中的数字,将字符串转换为列表 (lista),然后使用 map() 函数将新列表中的字符串转换为整数:

   str1="13,22,32,4,5"

   str2=str1.split()
   lista=list(str2)

   lista=map(int,lista)

   print sum(lista)

由于某种原因,我收到以下错误消息:“ValueError: invalid literal for int() with base 10: '13,22,32,4,5'”

【问题讨论】:

    标签: string list python-2.7


    【解决方案1】:

    使用split() 不会拆分str1,因为没有sep 参数,默认分隔符是空格' '。因此:

    str2 == ["13,22,32,4,5"]
    

    您需要指定split 应使用逗号','。事实上,您可以将您的操作合二为一:

    sum(map(int, str1.split(',')))
    

    【讨论】:

    • 我知道你在那里做了什么。我设法通过在拆分函数括号中添加 (",") 来完成我的工作。谢谢!
    • 您无需拨打lista = list(str2)split 返回一个列表,所以你可以使用lista = str1.split(',')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2017-07-30
    • 2015-01-14
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多