[Python-ideas] while conditional in list comprehension ??
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Mon Jan 28 22:22:09 CET 2013
>Ethan Furman <ethan at ...> writes:
>
> On 01/28/2013 05:33 AM, Wolfgang Maier wrote:
> > Consider this:
> >
> > some_names=["Adam", "Andrew", "Arthur", "Bob", "Caroline","Lancelot"] #
> > a sorted list of names
> > [n for n in some_names if n.startswith("A")]
> > # certainly gives a list of all names starting with A, but .
> > [n for n in some_names while n.startswith("A")]
> > # would have saved two comparisons
>
> What happens when you want the names that start with 'B'? The advantage
> of 'if' is it processes the entire list so grabs all items that match,
> and the list does not have to be ordered. The disadvantage (can be)
> that it processes the entire list.
>
> Given that 'while' would only work on sorted lists, and could only start
> from the beginning, I think it may be too specialized.
>
> But I wouldn't groan if someone wanted to code it up. :)
>
> +0
>
> ~Ethan~
>
I thought about this question, and I agree this is not what the while clause
would be best for.
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.
Best,
Wolfgang
More information about the Python-ideas
mailing list