could not convert string to float (python)

后端 未结 2 869
悲哀的现实
悲哀的现实 2021-01-29 14:54

I am trying to find the sum of all numbers in a list but every time I try I get an error that it cannot convert the string to float. Here is what I have so far.

         


        
相关标签:
2条回答
  • 2021-01-29 15:00

    'elec_used' is of type string of characters. You can not convert characters to the float. I am not sure why you thought you could do it. However you can convert the numeric string to float by typecasting it. For example:

    >>> number_string = '123.5'
    >>> float(number_string)
    123.5
    

    Now coming to your second part, for calculating the sum of number. Let say your are having the string of multiple numbers. Firstly .split() the list, type-cast each item to float and then calculate the sum(). For example:

    >>> number_string = '123.5 345.7 789.4'
    >>> splitted_num_string = number_string.split()
    >>> number_list = [float(num) for num in splitted_num_string]
    >>> sum(number_list)
    1258.6
    

    Which could be written in one line using list comprehension as:

    >>> sum(float(item) for item in number_string.split())
    1258.6
    

    OR, using map() as:

    >>> sum(map(float, number_string.split()))
    1258.6
    
    0 讨论(0)
  • 2021-01-29 15:20

    You need none of your code above. The while loop is unnecessary and it looks like its just exiting the loop in one iteration i.e. its not used correctly. If you're simply summing all the values in the list:

    sum([float(i) for i in elec_used])
    

    If this produces errors, please post your elec_used list. It probably contains string values or blank spaces.

    0 讨论(0)
提交回复
热议问题