2D List comprehension & replace

Paul McGuire bogus at bogus.net
Fri Mar 12 02:55:30 CET 2004


"Larry Bates" <lbates at swamisoft.com> wrote in message
news:ZOednXPakP64mczdRVn-jA at comcast.com...
> I should not have given up so soon.
>
> [[y or None for y in x] for x in l]
>
> seems to do the trick.
>
> -Larry Bates
>

Well if that works, then this must too:

     [y or None for x in l for y in x]

-- Paul


>
> "Larry Bates" <lbates at swamisoft.com> wrote in message
> news:YuSdndB1QM85nczd4p2dnA at comcast.com...
> > I've gone brain-dead trying to get this to work
> > using list comprehensions.  I have a list of lists
> > like the following:
> >
> > l=[[92.6, 0, 93.5],
> >    [94.7, 95.6, 95.7],
> >    [91.2, 92.1, 93.0]]
> >
> > what I want is a new list
> > with the zero (0) replaced with None.
> >
> > I thought I would use the fact that the command:
> >
> > 0 or None
> >
> > seems to return None.
> >
> > This procedural code does the trick, but I just
> > know it can be done with a single list comprehension.
> >
> > tol=[]
> > for a in l:
> >     til=[]
> >     for v in a:
> >         if a != 0: til.append(v)
> >         else:      til.append(None)
> >
> >     tol.append(til)
> >
> > l=tol
> >
> > Thanks in advance.
> >
> > Larry Bates
> >
> >
>
>





More information about the Python-list mailing list