How to parse a list of decimal numbers in python...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Lura
    New Member
    • May 2010
    • 1

    How to parse a list of decimal numbers in python...

    In an effort to learn how to work with information in files, I am writing a program that opens an already existing file containing decimal numbers. It then takes the decimals, sorts them, and returns median and mean.

    Here's what I have so far:

    Code:
    #opening file as a read only file
    f = open('testfile', 'r') 
    
    #assigns variable to string
    numbers = f.read(testfile) 
    
    #Make a list where each decimal is its own string 
    
    numbers.split(",")
    So...I have the list part accomplished. string.split(se p) yields the information as a list. But I don't know how to take these data from the list and make each decimal number it's own string.

    I am still a bit new to python, so maybe I am going about this the wrong way...or maybe it's obvious?
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi. You're doing it right so far.

    You need to convert the string to a float, with the float command. This can be done by looping over the string, or more efficiently with a so-called comprehension.

    Hopefully the following interactive session will help you:
    Code:
    In [15]: num=["1","2","3.45"]
    
    In [16]: type(num[0])
    Out[16]: <type 'str'>
    
    In [17]: num2=[float(item) for item in num]
    
    In [18]: num2
    Out[18]: [1.0, 2.0, 3.4500000000000002]
    
    In [19]: type(num2)
    Out[19]: <type 'list'>
    
    In [20]: type(num2[0])
    Out[20]: <type 'float'>
    Post back to let us know how it goes.

    Comment

    Working...