[Tutor] Loop optimization
wormwood_3 at yahoo.com
Mon Aug 20 16:26:24 CEST 2007
>I think what you have is pretty clear. I can't think of a way to do this
>with a single list comprehension because you add two items to the list
>each time through the loop. You could use a list comp and a generator
>expression, but the order of entries in the result will be different:
>self.potdomains = [ word + suffix1 for word in self.dictcontents ]
>self.potdomains.extend(word + suffix2 for word in self.dictcontents)
I see what you mean now. I think in this case adding a list comprehension into the mix makes it less readable!
>> or a generator,
> for word in words:
> yield word + suffix1
> yield word + suffix2
>self.potdomains = list(suffixGen(self.dictcontents))
To me, in terms of immediate readability, the generator version seems best, at least as you have written it.
>The only way to know for sure is to try it with your data. Use the
>timeit module to test.
It did not know of this module. It will be quite helpful, thanks! (I had been setting a variable to time.time() before a process I needed to time, and then another after, and subtracting them...:-) )
>This takes all attribute lookups out of the loop. Put this in a function
>(method) and make sure suffix1 and suffix2 are local variables (probably
>function parameters). Then test :-)
I will do so tonight and report back.
More information about the Tutor