Newbie Import two coloums of floating point data into python HOWTO

Jeff Shannon jeff at ccvcorp.com
Wed Mar 13 16:24:04 EST 2002


Andy Gimblett's code should work, but I'd do a few things a bit
differently...

Andy Gimblett wrote:

>     lines = input.readlines()
>     for line in lines:

It's also possible to do the readlines() as part of the for loop --

    for line in input.readlines():


>         if not line.strip():
>             # Skip blank line
>             continue

Unnecessary, because split() will accomplish the same ends as well.


>          (first, second) = line.split()
>         row = (float(first), float(second))
>         results.append(row)

These three lines can be replaced with

        results.append( map(float, line.split() ) )

and it *won't* error if there's not exactly two items in line.  The call
to map() applies the float() function to each item returned by
line.split(), and returns a list, which is then appended to results.  Note
that this makes results into a list of lists, rather than a list of
tuples.  If you care, you can nest a call to tuple() between the map() and
the append(), like so:

        results.append( tuple(map(float, line.split()) ) )

This is getting a bit too deeply nested to be easy to read, so it's also
reasonable to use a temporary variable to split this one into two lines
(simply for legibility):

        data = map(float, line.split())
        results.append(tuple(data))

One can also replace the map() with a list comprehension:

        data = [float(x) for x in line.split()]
    or
        results.append( tuple( [float(x) for x in line.split()] ) )

Of course, as noted, many of these are matters of personal taste.  Use or
not as you see fit.  :)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list