Basic question

Cesar G. Miguel cesar.gomes at gmail.com
Sun May 13 15:36:52 EDT 2007


On May 12, 8:13 pm, a... at mac.com (Alex Martelli) wrote:
> Cesar G. Miguel <cesar.go... at gmail.com> wrote:
>
> > On May 12, 3:40 pm, Dmitry Dzhus <m... at sphinx.net.ru> wrote:
> > > > Actually I'm trying to convert a string to a list of float numbers:
> > > > str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]
>
> > > str="53,20,4,2"
> > > map(lambda s: float(s), str.split(','))
>
> > > Last expression returns: [53.0, 20.0, 4.0, 2.0]
> > > --
> > > Happy Hacking.
>
> > > Dmitry "Sphinx" Dzhushttp://sphinx.net.ru
>
> > Nice!
>
> As somebody else alredy pointed out, the lambda is supererogatory (to
> say the least).
>
> > The following also works using split and list comprehension (as
> > suggested in a brazilian python forum):
>
> > -------------------
> > L = []
> > file = ['5,1378,1,9', '2,1,4,5']
> > str=''
> > for item in file:
> >       L.append([float(n) for n in item.split(',')])
>
> The assignment to str is useless (in fact potentially damaging because
> you're hiding a built-in name).
>
> L = [float(n) for item in file for n in item.split(',')]
>
> is what I'd call Pythonic, personally (yes, the two for clauses need to
> be in this order, that of their nesting).
>
> Alex

Yes, 'str' is unnecessary. I just forgot to remove it from the code.




More information about the Python-list mailing list