[Python-ideas] while conditional in list comprehension ??

Ethan Furman ethan at stoneleaf.us
Mon Jan 28 22:43:33 CET 2013


On 01/28/2013 01:22 PM, Wolfgang Maier wrote:
> However, currently you could solve tasks like this with itertools.takewhile in
> the following (almost perl-like) way (I illustrate things with numbers to keep
> it simpler):
>> l=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
> # now retrieve all numbers from 10 to 19 (combining takewhile and slicing)
> [n for n in itertools.takewhile(lambda n:n<20,l[len([x for x in
> itertools.takewhile(lambda x:x<10,l)]):])]
>> Nice, isn't it?
>> If I am not mistaken, then with my suggestion this would at least simplify to:
>> [n for n in l[len([x for x in l while x<10]):] while n<20]
>> Not great either, I admit, but at least it's fun to play this mindgame.

Well, as long as we're dreaming, how about
[n for n in l while 10 <= n < 20]
and somebody (else!) can code to skip until the first condition is met, 
then keep until the second condition is met, and then stop.
:)

~Ethan~


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /