rewrite for achieving speedup

Steven Bethard steven.bethard at gmail.com
Tue Apr 17 11:25:00 EDT 2007


Steve Holden wrote:
> Johnny Blonde wrote:
>> Hello Group!
>>
>> I really tried hard for two hours to rewrite the following expression
>> (python 2.4):
>> --------------------------
>> teilnehmer = []
>> for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS
>>> = datum)):
>>     for g in r.BUCHUNGEN:
>>         for t in g.aktiveTeilnehmer:
>>             teilnehmer.append(t)
>> --------------------------
>>
>> to something like
>> --------------------------
>> teilnehmer = [x for x in ........]
>> --------------------------
>>
>> Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and
>> BUCHUNGEN all are of the type SelectResults.
>>
>> unfortunately i just can´t figure it out to make it work.
>> i hope someone maybe can help me?
>>
>> I hope to gain performance by rewriting it...
>>
>> Thanks a lot for your help!
>>
>  >>> lt = [[[1,2,3], [2,3,4]], [[3,4,5], [4,5,6]]]
>  >>> lf = [c for a in lt for b in a for c in b]
>  >>> lf
> [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
>  >>>
> 
> Untested:
> 
> teilnehmer = [t for r in Reisen.select(AND(Reisen.q.RESVON <= datum, 
> reisen.q.RESBIS >= datum)) for g in r.BUCHUNGEN for t in 
> g.aktiveTeilnehmer]

Note also that you can probably get most of the speedup above by binding 
the append method to a function-local name::

     teilnehmer = []
     append = teilnehmer.append
     for r in Reisen.select(...):
         for g in r.BUCHUNGEN:
             for t in g.aktiveTeilnehmer:
                 append(t)

That's pretty much all a list comprehension is doing anyway.

STeVe



More information about the Python-list mailing list