faster than list.extend()
Hyunchul Kim
hyunchul.mailing at gmail.com
Tue Nov 17 03:07:42 EST 2009
Thank Tim, Raymond, and all.
In my test, Tim's t1 was fastest and Raymond's triple3 is very near to Tim's
t1.
Anyway both of them took only 6~7% time of my original .extend() version.
I think that following n_ple() is a good generalized function that was 1~3%
slower than t1() and triple3() for "triple".
*********
from itertools import *
def n_ple(inputlist, n):
chain_from_iterable = chain.from_iterable; izip = izip
return chain_from_iterable(izip(*[inputlist]*n))
*********
def t2(i):
r = range(3)
return (x for x in i for _ in r)
def t2_1(i):
r = range(3)
return [x for x in i for _ in r]
I didn't know that list(t2(inputlist)) is much faster than t2_1(inputlist),
it's gonna be a helpful tip for me.
Thank you all.
Hyunchul
On Tue, Nov 17, 2009 at 7:55 AM, Tim Chase <python.list at tim.thechases.com>wrote:
> Hyunchul Kim wrote:
>
>> Hi, all.
>>
>> I want to improve speed of following simple function.
>> Any suggestion?
>>
>> **********
>> def triple(inputlist):
>> results = []
>> for x in inputlist:
>> results.extend([x,x,x])
>> return results
>> **********
>>
>
> Several ways occur to me:
>
> def t1(i):
> for x in i:
> yield x
> yield x
> yield x
>
> def t2(i):
> r = range(3)
> return (x for x in i for _ in r)
>
>
> I prefer to return generators in case the input is large, but in both
> cases, you can just wrap it in list() like
>
> list(t1(inputlist))
>
> or in t2(), you can just change it to use
>
> return [x for x in i for _ in r]
>
> -tkc
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091117/c7e0c5fa/attachment-0001.html>
More information about the Python-list
mailing list