3

我真的是编程的初学者。我想打印字符串 s = '1.23,2.4,3.123' 的总和。我试着用

total = 0.0
for s in '1.23,2.4,3.123':
    total += float(s)
print total

但它不起作用,有人可以帮忙吗?多谢

4

4 回答 4

3

您可以尝试以下方法:

total = sum(float(i) for i in s.split(','))

它像这样运行:

  • s.split(',')提取字符串中的每个“数字”

  • float(i) for i in s...对每个拆分值进行浮点运算

  • sum()把它们加起来

希望这可以帮助!

于 2013-04-25T23:36:33.343 回答
1
s = '1.23,2.4,3.123'
nums = [float(i) for i in s.split(',')] # creates a list of floats split by ','
print sum(nums) # prints the sum of the values
于 2013-04-25T23:35:37.097 回答
1
>>> str_list = '1.23,2.4,3.123'.split(',')
>>> float_list = [float(str_number) for str_number in str_list]
>>> total = sum(float_list)
>>> print total
于 2013-04-25T23:43:15.263 回答
1

我会这样做:

sum(map(float, s.split(',')))
于 2013-04-25T23:44:26.763 回答