[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Convert string item in a list into floats

Posted on 2011-04-23
5
Medium Priority
?
621 Views
Last Modified: 2012-05-11
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

0
Comment
Question by:Enzo255
  • 3
5 Comments
 
LVL 5

Accepted Solution

by:
-Richard- earned 2000 total points
ID: 35454048
You are correct, you are missing just one line of code.  The problem is that the readlines() method reads all the lines in a file at once, and puts them into an array, each element of which contains one entire line.  Your outermost loop is traversing the list of full lines in the file (which in this case would be just one line), and yes, you are processing the whole line at once.  Try the following:

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

Author Closing Comment

by:Enzo255
ID: 35454109
Oh I see, thanks a lot man!
0
 
LVL 29

Expert Comment

by:pepr
ID: 35454357
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

0
 
LVL 29

Expert Comment

by:pepr
ID: 35454372
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

0
 
LVL 29

Expert Comment

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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses
Course of the Month20 days, 3 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question