[Tutor] assigning types(?) to list elements

Magnus Lycka magnus@thinkware.se
Tue, 15 Oct 2002 11:39:47 +0200


At 15:24 2002-10-14 +0200, Fran=E7ois Granger wrote:
>on 14/10/02 14:08, Joseph Paish at jpaish@freenet.edmonton.ab.ca wrote:
>
> > file_handle =3D open ('/path/to/datafile.txt', 'r')
> >
> > for each_line in file_handle.readlines() :
> >       each_line =3D each_line.rstrip() # strip off carriage return
> >       temp1, temp2, temp3, temp4, temp5, temp6 =3D=
 string.split(each_line)
> >       temp2  =3D float(temp2)
> >       temp3  =3D int(temp3)
> >       temp4  =3D int(temp4)
> >       temp5 =3D float(temp5)
> >       temp6 =3D float(temp6)
>
>This seems to do what you want:
>
>typeslist =3D [str,float,int,int,float,float]
>
>test =3D 'abc 123.45 74 98 234.56 345.67'
>temp =3D test.split()
># a sample record is : 'abc 123.45 74 98 234.56 345.67'
>result =3D []
>for i in range(len(temp)):
>     result.append(typeslist[i](temp[i]))

With a current python installation you can do
(untested):

typeslist =3D [str,float,int,int,float,float]
for each_line in file('/path/to/datafile.txt', 'r'):
     # Split will remove the trailing \n
     values =3D [Type(Value) for (Type, Value) in
               zip(typeslist, each_line.split())]
     ...whatever...


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se