Python将字符串文字转换为浮点数

5
我正在学习古塔格博士的《使用Python进行计算和编程入门》一书,并且正在完成第三章的练习。我遇到了麻烦,具体而言是在第25页的第3.2节中。练习要求:定义一个字符串s,其中包含由逗号分隔的一系列十进制数字,例如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."的错误信息。

将字符串转换为浮点数使用>>> a = "1.23" float(a)
1.23。如果有多个字符串,则拆分它们并使用float函数。
- Vinayak Pingale
一个提示:看一下代码片段 total += cc 是一个字符串,所以你试图将一个字符串加到一个整数 total 上。 - richizy
24个回答

6

浮点数值不能有逗号。你正在将 1.23,2.4,3.123 直接传递给浮点数函数,这是不合法的。首先根据逗号分割字符串,

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

然后将列表中的每个元素转换为浮点数,并将它们加在一起以获得结果。为了感受 Python 的威力,可以按以下方式解决这个特定问题。

您可以像这样找到 总和

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)

我可以问一下吗:total = sum([float(item) for item in s.split(",")]);和total = sum(float(item) for item in s.split(","))之间有什么区别? - user1825083
1
@KennyLJ 第一个使用List Comprehension,第二个使用Generator Expression - thefourtheye
@MartijnPieters 谢谢 :) 我已经修复了。 - thefourtheye

4

既然您正在学习Python,可以尝试以下简单方法:

使用split(c)函数,其中c是一个分隔符。这样,您将得到一个名为numbers的列表(如下面的代码所示)。然后,您可以遍历该列表中的每个元素,将每个数字强制转换为float(因为numbers的元素是字符串),并将它们相加:

numbers = s.split(',')
sum = 0

for e in numbers:
    sum += float(e)

print sum

输出:

6.753

3

来自书籍使用Python进行计算和编程入门第25页。

"假设s是一个包含由逗号分隔的十进制数字序列的字符串,例如,s = '1.23,2.4,3.123'。编写一个程序,打印出s中数字的总和。"

如果仅使用目前所学的知识,那么这段代码是一个方法:

tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
    if ch != ',':
        tmp = tmp + ch
    elif ch == ',':
        num = num + float(tmp)
        tmp = ''

# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))

2
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
    total = total + float(c)
print(total)

1
我认为自从这个问题被提出(以及其他人的回答)以来,他们已经修订了这本教科书。我有这本教材的第二版,但是在第25页上没有分割示例。在此课程之前,没有任何内容向您展示如何使用split。
最终,我找到了另一种使用正则表达式完成它的方法。以下是我的代码:
# Intro to Python
# Chapter 3.2
# Finger Exercises

# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
    total = total + float(s)
print(total)

在学习新事物方面,我从未认为自己是愚钝的,但到目前为止,这本书中(大部分)手指练习让我感到困难。


1
像魔法一样好用 只使用了我已经学过的东西
    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

1
s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
    if c != ',':
        x = x + c
    else:
        sum = sum + float(x)
        x = ''  
sum = sum + float(x)        
print(sum)  

这只是使用书中已经介绍的想法。基本上,它通过遍历原始字符串s中的每个字符,使用字符串加法将每个字符添加到下一个字符来构建一个新字符串x,直到遇到逗号为止,在这一点上,它将x更改为浮点数并将其添加到从零开始的总和变量中。然后它将x重置为空字符串并重复此过程,直到覆盖了s中的所有字符。

1
这是我想出来的内容:
s = raw_input('Enter a sequence of decimal numbers separated by commas: ')
aux = ''
total = 0
for c in s:
    aux = aux + c
    if c == ',':
        total = total + float(aux[0:len(aux)-1])
        aux = ''
total = total + float(aux) ##Uses last value stored in aux
print 'The sum of the numbers entered is ', total

1
尽量详细地解释你所做的事情,而不是仅凭代码作为解释。 - Passer By

0

我已经通过学习3.2章节的循环部分,成功回答了该问题。

s = '1.0, 1.1, 1.2'
print 'List of decimal number' 
print s 
total = 0.0
for c in s:
    if c == ',':
       total += float(s[0:(s.index(','))])
       d = int(s.index(','))+1
       s = s[(d+1) : len(s)]

s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total  

这是答案,我觉得split函数并不适合像你我这样的初学者。


0

我的答案在这里:

s = '1.23,2.4,3.123'

sum = 0
is_int_part = True
n = 0
for c in s:
    if c == '.':
        is_int_part = False
    elif c == ',':
        if is_int_part == True:
            total += sum
        else:
            total += sum/10.0**n
        sum = 0
        is_int_part = True
        n = 0
    else:
        sum *= 10
        sum += int(c)
        if is_int_part == False:
            n += 1
if is_int_part == True:
    total += sum
else:
    total += sum/10.0**n
print total

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接