[Tutor] Skipping elements from inside generator loops
lonetwin
lonetwin <lonetwin@subdimension.com>
Thu, 1 Aug 2002 15:07:21 +0530 (IST)
Hi there,
I'm answering this just b'cos I love using list comprehensions ....
On Thu, 1 Aug 2002, Scot W. Stevenson wrote:
>Hello there,
>
>So here I am playing around with generators, and just for the heck of it I
>see if I can get a for-loop to skip one element from inside the loop. To
>my surprise, this works (in Python 2.2):
>
......
......
>procession= ['black cat',
> 'white cat',
> 'grey cat',
> 'ALARM!',
> 'the evil dog',
> 'fat cat',
> 'slow cat']
......
......
>[While we're at it: I assume that there is a way to solve the problem with
>list comprehensions, but I can't figure it out. Note that looking for the
>dog directly is considered cheating: All you get to do is skip one list
>entry when somebody sounds the alarm.]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cat_list = [ cat for cat in procession if cat != 'ALARM!' and cat != 'the evil dog' ]
for cat in cat_list:
print cat
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note: and for all those ppl who think list comprehensions are hard to
read, try imagining a ":" like I've added below, I think that looks more
sensible/pythonic.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cat_list = [ cat : for cat in procession if cat != 'ALARM!' and cat != 'the evil dog' ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Peace
Steve
--
This is the tomorrow you worried about yesterday. And now you know why.