我真的是编程的初学者。我想打印字符串 s = '1.23,2.4,3.123' 的总和。我试着用
total = 0.0
for s in '1.23,2.4,3.123':
total += float(s)
print total
但它不起作用,有人可以帮忙吗?多谢
我真的是编程的初学者。我想打印字符串 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(',')))