我是 Python 的新手,我遇到了一个问题。我正在尝试将一串数字转换为 int 或 float,以便我可以将它们相加。这是我的第一个问题/帖子。非常感谢任何建议!
total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'
for i in s:
total += int(i)
print total
我得到错误:
*3
4 for i in s:
----> 5 total += int(i)
6 print total
ValueError: invalid literal for int() with base 10: ','*
请您参考如下方法:
您需要使用 str.split 在逗号处拆分字符串.然后,将它们转换为 float (我不知道当你说要将它们转换为“int 或 float”时为什么要使用 int)。
total = 0
s = '2, 3.4, 5, 3, 6.2, 4, 7'
for i in s.split(','):
total += float(i)
print total
就个人而言,我更愿意使用生成器表达式来执行此操作:
s = '2, 3.4, 5, 3, 6.2, 4, 7'
total = sum(float(i) for i in s.split(','))
print total
您所做的不起作用的原因是 for i in s 遍历 s 的每个单独字符。所以首先它会执行 total += int('2'),这是有效的。但随后它尝试 total += int(','),这显然不起作用。
