【发布时间】:2015-10-11 16:10:17
【问题描述】:
我正在学习使用 John V. Guttag 所著的“Python 计算和编程简介”一书进行编程。上面有一个练习,内容如下:
'手指练习:设 s 是一个包含一系列 用逗号分隔的十进制数,例如 s = '1.23,2.4,3.123'。写 打印 s 中数字之和的程序。'
我的尝试是:
#Finger exercise [MIT] PAGE 42 12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
total = 0
for l in range(0,len(s)):
if s[l] == ',':
c = l + 1
while s[c] != ',':
c = c + 1
if s[c] == ',':
total = total + int(s[int(l),int(c)])
print total
但它一直显示此错误
TypeError:字符串索引必须是整数,而不是元组
我尝试在网上寻求解决方案,但只找到了可行的解决方案但不适用于我现在已经提供的内容。 有什么帮助吗?
【问题讨论】:
-
等你了解了基础知识后,试试这个
sum(map(float,s.split(',')))。单行工作