我正在阅读Guttag博士的书“使用Python进行计算和编程的简介”。我正在做第三章的手指练习,我被卡住了。是第25页的3.2节。练习是:假设一个字符串包含一个用逗号分隔的十进制数字序列,例如s = '1.23,2.4,3.123'
。编写一个程序,打印s中数字的求和。
前面的示例是:
total = 0
for c in '123456789':
total += int(c)
print total.
我试了一次又一次,但一直收到各种错误。这是我最新的尝试。
total = 0
s = '1.23,2.4,3.123'
print s
float(s)
for c in s:
total += c
print c
print total
print 'The total should be ', 1.23+2.4+3.123
我得到了ValueError: invalid literal for float(): 1.23,2.4,3.123.
发布于 2014-01-19 11:07:16
浮点值不能有逗号。您正在将1.23,2.4,3.123
原样传递给浮点函数,这是无效的。首先根据逗号拆分字符串,
s = "1.23,2.4,3.123"
print s.split(",") # ['1.23', '2.4', '3.123']
然后将该列表中的每个和和每个元素转换为浮点型,并将它们相加得到结果。为了感受Python的威力,这个特殊的问题可以通过以下方式解决。
您可以找到total
,如下所示
s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))
如果元素的数量太大,可以使用生成器表达式,如下所示
total = sum(float(item) for item in s.split(","))
所有这些版本都将产生相同的结果
total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
total += float(current_number)
发布于 2015-12-25 16:34:22
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
total = total + float(c)
print(total)
发布于 2015-09-12 01:53:35
像魔符这样的作品只用了我学到的东西
s = raw_input('Enter a string that contains a sequence of decimal ' +
'numbers separated by commas, e.g. 1.23,2.4,3.123: ')
s = "," + s+ ","
total =0
for i in range(0,len(s)):
if s[i] == ",":
for j in range(1,(len(s)-i)):
if s[i+j] == ","
total = total + float(s[(i+1):(i+j)])
break
print total
https://stackoverflow.com/questions/21212706
复制相似问题