Rob Blaze
Rob Blaze

Reputation: 43

Can't convert a list of strings to floats

My program is supposed to read a text document with a bunch of numbers and make a list of only the positive numbers. I can't convert the strings from the text document to a float so i can't determine if they are postive.

I linked a screenshot because my copy paste is buggy.

https://i.sstatic.net/L1Z7z.png

https://i.sstatic.net/L1Z7z.png

Without the number = float(number) , I get ['3.7', '-22', '3500', '38', '-11.993', '2200', '-1', '3400', '3400', '-3400', '-22', '12', '11', '10', '9.0']

Upvotes: 3

Views: 21227

Answers (3)

orlp
orlp

Reputation: 118006

First of all, don't call variables list, you will hide the built-in list with that.

Here is an improvement:

li = []

for line in open("numbers.txt"):
    nums = line.split() # split the line into a list of strings by whitespace
    nums = map(float, nums) # turn each string into a float
    nums = filter(lambda x: x >= 0, nums) # filter the negative floats

    li.extend(nums) # add the numbers to li

Upvotes: 2

dhg
dhg

Reputation: 52701

You can translate that list into floats easily:

>>> nums = ['3.7', '-22', '3500', '38', '-11.993', '2200', '-1', '3400', '3400', '-3400', '-22', '12', '11', '10', '9.0']
>>> map(float, nums)
[3.7, -22.0, 3500.0, 38.0, -11.993, 2200.0, -1.0, 3400.0, 3400.0, -3400.0, -22.0, 12.0, 11.0, 10.0, 9.0]

But the problem seems to be that the lines in your file don't contain individual floats. When you call float(number), number is a line from the file, which (from the error) appears to contain three space-separated numbers "3.7 -22 3500".

What you need is to call the float function after splitting:

for line in f:
  for numberString in line.split()
    number = float(numberString)
    if(number > 0)
      numbers.append(number)

Or, more functionally:

for line in f:
  numbers.extend([n for n in map(float, line.split()) if n > 0])

Upvotes: 5

Simeon Visser
Simeon Visser

Reputation: 122536

After reading the contents of the file, you need to split the contents by spaces and parse each number separately. It is now trying to parse the string '3.7 -22 3500' as a single float which is not possible.

>>> float('3.7 -22 3500')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 3.7 -22 3500

Upvotes: 2

Related Questions