is there a better way?
Steve Holden
steve at holdenweb.com
Fri Feb 10 14:06:26 EST 2006
markscala at gmail.com wrote:
> 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.
>>> X = "X"
>>> O = "O"
>>> def fl(l):
... for i, v in enumerate(l):
... if v == O:
... return l[:i]
... return l
...
>>> fl([X,X,X,X,O,O,O])
['X', 'X', 'X', 'X']
>>> fl([])
[]
>>> fl([O])
[]
>>> fl([X])
['X']
>>>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list