字符串的和包含一个十进制数字序列



我在编程方面确实是个新手。我想打印字符串s = '1.23,2.4,3.123'的和。我试着用

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

但是它不起作用,有人能帮忙吗?非常感谢

您可以尝试以下操作:

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

它是这样运行的:

  • s.split(',')取出字符串中的每个"数字"

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

  • sum()加起来

希望这对你有帮助!

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
>>> 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

我会这样做:

sum(map(float, s.split(',')))

最新更新