[Tutor] Skipping elements from inside generator loops
Gregor Lingl
glingl@aon.at
Sat, 03 Aug 2002 23:05:54 +0200
>
>
>>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>cat_list = [ cat for cat in procession if cat != 'ALARM!' and cat !=
>>'the evil dog' ] for cat in cat_list:
>> print cat
>>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>
>>
>
>Ah, but this is cheating - you are looking for 'the evil dog' directly.
>You
>are only allowed to check for the alarm, not for the dog itself!
>
>Y, Scot
>
>
What about this:
>>> p = ['black cat',
'white cat',
'grey cat',
'ALARM!',
'the evil dog',
'fat cat',
'slow cat']
Now one observes, that in
>>> zip([None]+p,p)
[(None, 'black cat'), ('black cat', 'white cat'), ('white cat', 'grey
cat'),
('grey cat', 'ALARM!'), ('ALARM!', 'the evil dog'), ('the evil dog',
'fat cat'),
('fat cat', 'slow cat')]
the second Element of each pair is good if only 'ALARM!' does not occur
in the pair:
>>> [pair[1] for pair in zip([None]+p,p) if 'ALARM!' not in pair]
['black cat', 'white cat', 'grey cat', 'fat cat', 'slow cat']
Not very elegant! Amendments?
Gregor