is there a better way?

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Feb 10 13:22:55 EST 2006


"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
news:PO4Hf.4221$UN2.1478 at tornado.texas.rr.com...
> <markscala at gmail.com> wrote in message
> news:1139594221.696053.7360 at g47g2000cwa.googlegroups.com...
> > Problem:
> >
> > You have a list of unknown length, such as this: list =
> > [X,X,X,O,O,O,O].  You want to extract all and only the X's.  You know
> > the X's are all up front and you know that the item after the last X is
> > an O, or that the list ends with an X.  There are never O's between
> > X's.
> >
> > I have been using something like this:
> > _____________________
> >
> > while list[0] != O:
> >     storage.append(list[0])
> >     list.pop(0)
> >     if len(list) == 0:
> >         break
> > _____________________
> >
> > But this seems ugly to me, and using "while" give me the heebies.  Is
> > there a better approach?
> >
> > hope this is clear.
> > thanks
> >
> Use itertools.
>
> >>> import itertools
> >>> lst = "X,X,X,O,O,O,O,O,X,X,X,X,O,X".split(",")
> >>> [z for z in itertools.takewhile(lambda x:x=="X",lst)]
> ['X', 'X', 'X']
>
>
> -- Paul
>

duh, last line should be:

>>> list(itertools.takewhile(lambda x:x=="X",lst))
['X', 'X', 'X']

(Also, don't name variables "list")

-- Paul





More information about the Python-list mailing list