result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)]
is a good approach but it is taking little more time than the for loop over
iterator.
def takewhile(predicate, iterable):
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
for x in iterable:
if predicate(x):
yield x
else:
break
I don't know why? As it seems that this for loop and the other for loop
doing the same thing.
--nitin
On Fri, Aug 20, 2010 at 9:17 PM, bob gailer <[email protected]> wrote:
> On 8/20/2010 5:44 AM, Steven D'Aprano wrote:
>
>> On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote:
>>
>>> "Steven D'Aprano"<[email protected]> wrote
>>>
>>> the purpose). No matter how fast you can perform a loop, it's
>>>> always faster to avoid it altogether, so this:
>>>>
>>>> seq = xrange(10000000)
>>>> result = []
>>>> for i in seq:
>>>> if i>= 10: break
>>>> result.append(i%2)
>>>>
>>>>
>>>> will be much faster than this:
>>>>
>>>> seq = xrange(10000000)
>>>> result = [i%2 for i in seq if i< 10]
>>>>
>>> Although it should be pointed out that these are doing very different
>>> things.
>>>
>> Well yes, but I pointed out that you *can* bail out early of for-loops,
>> but not list comprehensions. The whole point is with a list comp,
>> you're forced to iterate over the entire sequence, even if you know
>> that you're done and would like to exit.
>>
>> Take a look at itertools.takewhile!
>
> result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)]
>
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist - [email protected]
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor