Newbie question

Larry Bates lbates at websafe.com
Mon Mar 5 12:47:06 EST 2007


Tommy Grav wrote:
> Hi list,
> 
>    this is somewhat of a newbie question that has irritated me for a while.
> I have a file test.txt:
> 
> 0.3434  0.5322 0.3345
> 1.3435  2.3345 5.3433
> 
> and this script
> lines = open("test.txt","r").readlines()
> for line in lines:
>    (xin,yin,zin) = line.split()
>    x = float(xin)
>    y = float(yin)
>    z = float(zin)
> 
> Is there a way to go from line.split() to x,y,z as floats without
> converting
> each variable individually?
> 
> Cheers
>    Tommy


Using a list comprehension you would write this as:

for line in lines:
    xin, yin, zin=[float(x) for x in line.split()]

This if course expects your data to be perfect.  If
you want error handling (e.g. less or more than 3 values,
values that cause exception when passed to float, etc.)
you will have to handle that differently.

-Larry



More information about the Python-list mailing list