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.
http://i.stack.imgur.com/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']
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])
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.