【问题标题】:Python Convert String Literal to FloatPython将字符串文字转换为浮点数
【发布时间】:2014-01-19 03:03:31
【问题描述】:

我正在阅读 Guttag 博士的“Python 计算和编程简介”一书。我正在为第 3 章做手指练习。我卡住了。这是第 3.2 节,第 25 页。练习是:让 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.

【问题讨论】:

  • conert 字符串使用 >>> a = "1.23" float(a) >>1.23 浮动。如果在您的情况下有多个字符串,则将它们拆分并使用 float 函数。
  • 一个提示:查看sn-p total += c。 c 是一个字符串,因此您尝试将字符串添加到整数 total。

标签: python string literals


【解决方案1】:

浮点值不能有逗号。您将 1.23,2.4,3.123 传递给 float 函数,这是无效的。首先根据逗号分割字符串,

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

然后将该列表的每个元素转换为浮点数并将它们加在一起以获得结果。要感受 Python 的强大,可以通过以下方式解决这个特殊问题。

你可以找到total,像这样

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(",")]); 有什么区别? and total = sum(float(item) for item in s.split(","))
  • @KennyLJ 第一个使用List Comprehension,第二个使用Generator Expression
  • @MartijnPieters 谢谢 :) 我修好了。
【解决方案2】:

由于您是从 Python 开始的,您可以尝试这种简单的方法:

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

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

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

print sum

输出:

6.753

【讨论】:

    【解决方案3】:

    摘自Introduction to Computation and Programming using 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))
    

    【讨论】:

      【解决方案4】:
      total = 0
      s = '1.23,2.4,3.123'
      for c in s.split(','):
          total = total + float(c)
      print(total)
      

      【讨论】:

        【解决方案5】:

        像魅力一样工作 只用了我学到的东西

            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
        

        【讨论】:

          【解决方案6】:

          这是我想出的:

          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
          

          【讨论】:

          • 尽量详细解释你做了什么,而不是假设代码就足够解释了。
          【解决方案7】:

          我认为自从提出这个问题以来他们已经修改了这本教科书(并且其他一些人已经回答了。)我有第二版的文本,拆分示例不在第 25 页。本课之前没有任何内容这向您展示了如何使用拆分。

          我最终找到了一种使用正则表达式的不同方法。这是我的代码:

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

          在学习新事物方面,我从不认为自己很密集,但到目前为止,我对本书中的(大部分)手指练习感到很困难。

          【讨论】:

            【解决方案8】:
            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 的内容更改为浮点数并将其添加到从零开始的 sum 变量。然后它将 x 重置为空字符串并重复直到 s 中的所有字符都被覆盖

            【讨论】:

              【解决方案9】:

              这是一个不使用split的解决方案:

              s='1.23,2.4,3.123,5.45343'
              pos=[0]
              total=0
              for i in range(0,len(s)):
                  if s[i]==',':
                      pos.append(len(s[0:i]))
              pos.append(len(s))
              for j in range(len(pos)-1):
                  if j==0:
                      num=float(s[pos[j]:pos[j+1]])
                      total=total+num
                  else:
                      num=float(s[pos[j]+1:pos[j+1]])
                      total=total+num     
              print total
              

              【讨论】:

                【解决方案10】:

                我的方法有效:

                s = '1.23, 211.3'
                total = 0
                for x in s:
                    for i in x:
                        if i != ',' and i != ' ' and i != '.':
                            total = total + int(i)
                print total
                

                【讨论】:

                • 您添加的是字符串中的所有整数,而不是两个浮点数!
                【解决方案11】:

                我的答案在这里:

                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
                

                【讨论】:

                  【解决方案12】:

                  我已经设法用直到 3.2 节 for loop 获得的知识回答了这个问题

                  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  
                  

                  这是我觉得拆分功能不适合你我这样的初学者的问题的答案。

                  【讨论】:

                    【解决方案13】:

                    考虑到您可能还没有接触过更复杂的功能,不妨试试这些吧。

                    total = 0
                    for c in "1.23","2.4",3.123":
                        total += float(c)
                    print total
                    

                    【讨论】:

                      【解决方案14】:

                      我的回答:

                      s = '2.1,2.0'
                      countI = 0
                      countF = 0
                      totalS = 0
                      
                      for num in s:
                          if num == ',' or (countF + 1 == len(s)):
                              totalS += float(s[countI:countF])
                              if countF < len(s):
                                  countI = countF + 1
                          countF += 1
                      
                      print(totalS) # 4.1
                      

                      这只有在数字是浮点数时才有效

                      【讨论】:

                        【解决方案15】:

                        这是我的答案。它与上面 user5716300 的类似,但由于我也是初学者,我明确为拆分字符串创建了一个单独的变量 s1:

                        s = "1.23,2.4,3.123"
                        s1 = s.split(",")      #this creates a list of strings
                        
                        count = 0.0
                        for i in s1:
                            count = count + float(i)
                        print(count)
                        

                        【讨论】:

                          【解决方案16】:

                          如果我们只是坚持那一章的内容,我想出了这个:(虽然使用 theFourthEye 提到的 sum 方法也很漂亮):

                          s = '1.23,3.4,4.5'
                          result = s.split(',')
                          result = list(map(float, result))
                          n = 0
                          add = 0
                          for a in result:
                              add = add + result[n]
                              n = n + 1
                          print(add)
                          

                          【讨论】:

                            【解决方案17】:

                            我只想发布我的答案,因为我现在正在阅读这本书。

                            s = '1.23,2.4,3.123'
                            
                            ans = 0.0
                            i = 0
                            j = 0
                            for c in s:
                                if c == ',':
                                    ans += float(s[i:j])
                                    i = j + 1
                                j += 1
                            ans += float(s[i:j])
                            print(str(ans))
                            

                            【讨论】:

                              【解决方案18】:

                              使用书中的知识:

                              s = '4.58,2.399,3.1456,7.655,9.343'
                              total = 0
                              index = 0
                              for string in s:
                                  index += 1
                                  if string == ',':
                                      temp = float(s[:index-1])
                                      s = s[index:]
                                      index = 0
                                      total += temp
                                      temp = 0
                              print(total)
                              

                              这里我使用了字符串切片,每次我们的'string'变量等于','时切片原始字符串。还使用索引变量来跟踪逗号之前的数字。对字符串进行切片后,输入到 tmp 中的数字会被前面的逗号清除,字符串变成另一个没有该数字的字符串。

                              因此,每次发生这种情况时都需要重置索引变量。

                              【讨论】:

                                【解决方案19】:

                                这是我在问题中使用的确切字符串,并且仅使用了到目前为止所教的内容。

                                total = 0
                                temp_num = ''
                                
                                for char in '1.23,2.4,3.123':
                                    if char == ',':
                                        total += float(temp_num)
                                        temp_num = ''
                                    else:
                                        temp_num += char
                                
                                total += float(temp_num) #to catch the last number that has no comma after it
                                
                                print(total)
                                

                                【讨论】:

                                  【解决方案20】:

                                  我知道到目前为止这本书还没有涉及到,但我碰巧在回答这个问题之前自己学习了 eval() 函数的用法并用它来解决。

                                  total = 0
                                  s = "1.23,2.4,3.123"
                                  x = eval(s)
                                  y = sum(x)
                                  print(y)
                                  

                                  【讨论】:

                                    【解决方案21】:

                                    我认为这是回答问题的最简单方法。它使用了split命令,这本书暂时没有介绍,但是一个非常有用的命令。

                                    s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
                                    sList = s.split(',') #create a list of these values
                                    print(sList) #to check if list is correctly created
                                    
                                    total = 0 #for creating the variable
                                    
                                    for each in sList: 
                                        total = total + float(each)
                                    
                                    print(total)
                                    

                                    【讨论】:

                                    • 您的答案对现有的几个相同答案有何补充?
                                    【解决方案22】:
                                    total =0
                                    s = {1.23,2.4,3.123}
                                    for c in s:
                                        total = total+float(c)
                                    print(total)
                                    

                                    【讨论】:

                                    • 这没有回答原来的问题。
                                    猜你喜欢
                                    • 2011-11-25
                                    • 2019-07-10
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    相关资源
                                    最近更新 更多