[ x for x in xrange(10) when p(x) ]
Steve Holden
steve at holdenweb.com
Wed Nov 9 23:12:46 EST 2005
George Sakkis wrote:
> "bonono at gmail.com" wrote:
>
>
>>Alex Martelli wrote:
>>
>>>This becomes a valid list comprehension by writing 'if' instead of
>>>'when'.
>>
>>valid, yes. efficient, I am not sure.
>>
>>[ x for x in xrange(10000000) if p(x) ]
>>
>>means I need to go through the whole range even if p = lambda x: x < 2
>
>
> Itertools is your friend in this case:
>
>>>>from itertools import takewhile
>>>>list(takewhile(p, xrange(10000000)))
>
> [0, 1]
Maybe, but the code also implies an esoteric knowledge that the trught
value of the predicate is monotonically decreasing (in a Boolean sense).
This would not be true if (e.g.) p = lambda x: x % 2 == 0. So while
itertools.takewhile can save you unnecessary computations, such savings
rely on provable conditions of the predicate which are frequently false.
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