Python将字符串文字转换为浮点数 [英] Python Convert String Literal to Float

查看:1026
本文介绍了Python将字符串文字转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Guttag博士的《使用Python计算和编程入门》一书.我正在为第3章进行手指练习.我被困住了.它是第25页的3.2节.练习是:让s是一个字符串,其中包含一个用逗号分隔的十进制数字序列,例如s = '1.23,2.4,3.123'.编写一个程序,打印s中的数字之和.

I am working through the book "Introduction to Computation and Programming Using Python" by Dr. Guttag. I am working on the finger exercises for Chapter 3. I am stuck. It is section 3.2, page 25. The exercise is: Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sume of the numbers in s.

上一个示例是:

total = 0
for c in '123456789':
    total += int(c)
print total.

我已经尝试了很多次,但是不断出现各种错误.这是我最近的尝试.

I've tried and tried but keep getting various errors. Here's my latest attempt.

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.

推荐答案

浮点值不能带有逗号.您正在按1.23,2.4,3.123传递浮点函数,这是无效的.首先根据逗号分割字符串,

Floating point values cannot have a comma. You are passing 1.23,2.4,3.123 as it is to float function, which is not valid. First split the string based on comma,

s = "1.23,2.4,3.123"
print s.split(",")        # ['1.23', '2.4', '3.123']

然后将列表中的每个元素转换为float并将它们加在一起以得到结果.为了感受到Python的强大功能,可以通过以下方式解决此特定问题.

Then convert each and and every element of that list to float and add them together to get the result. To feel the power of Python, this particular problem can be solved in the following ways.

您可以找到total,就像这样

s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))

如果元素数量太大,则可以使用生成器表达式,像这样

If the number of elements is going to be too large, you can use a generator expression, like this

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)

这篇关于Python将字符串文字转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆