Link to home
Start Free TrialLog in
Avatar of Enzo255
Enzo255

asked on

Convert string item in a list into floats

Hello,

Can someone please give me the code I am missing in this function?
It seems like its just taking the numbers as a whole string instead of the individual characters.
The text file I created contains "12,10,9,7,11,9,9,11,9,12,9,8,7,8,7,11,8,10,12,8,11,10,12,12,11,12,8,8" in the text file.
I feel like I'm missing one line of code, and I don't know that it is.  I'm trying to get a list of floats, each individual items.

def fileload():
    file=raw_input("Enter text file name: ")
    infile = open(file, "r")
    num = infile.readlines()
    numlist=[]
    for item in num:
        newnum=float(item)
        numlist.append(newnum)
    numlist.sort()
    return numlist
      
fileload()

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of -Richard-
-Richard-
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Enzo255
Enzo255

ASKER

Oh I see, thanks a lot man!
Avatar of pepr
There are things to be improved.  If only the first line is to be read, try the following:

a.py
def load(fname):
    f = open(fname)     # do not use the 'file' identifier (it is a class/type identifier)
    line = f.readline() # read the single line
    f.close()           # it is always good to close the open file
    lst = [float(e) for e in line.split(',')] # split and convert to floats (list comprehension)
    lst.sort()          # sort the elements in situ         
    return lst     
      

fname = raw_input("Enter text file name: ")  # better to get fname outside the function
lst = load(fname)
print lst

Open in new window


It prints in my case:

C:\tmp\_Python\Enzo255\Q_26973710>python a.py
Enter text file name: data.txt
[7.0, 7.0, 7.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 9.0, 9.0, 9.0, 9.0, 9.0, 10.0, 
10.0, 10.0, 11.0, 11.0, 11.0, 11.0, 11.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0]

Open in new window

If you want to read all lines and extend the content of the resulting list, you can also use the .extend() method of a list.  The generator expression can be used for conversion of the line:

b.py
def load(fname):
    f = open(fname)     # open the fname
    lst = []            # init -- empty list
    for line in f:      # loop through read the single line
        lst.extend(float(e) for e in line.split(',')) # convert another line
    f.close()           # it is always good to close the open file
    return sorted(lst)  # can be used since Python 2.4     
      

fname = raw_input("Enter text file name: ")  # better to get fname outside the function
lst = load(fname)
print lst

Open in new window

Sorry.  The comment of the line 4 should read: loop through all the lines of the file (copy error).