[Tutor] List comp question
Alan Gauld
alan.gauld at btinternet.com
Sat Nov 3 01:49:18 CET 2007
"Kent Johnson" <kent37 at tds.net> wrote
> I would really like to turn this into a list comprehension:
>
> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>
> but the call to level2() is expensive enough that I don't want to
> repeat
> it. Is there any way to do this or am I stuck with the (IMO ugly)
> loop form?
Not sure how this would work but you might be able to use
a temporary global var to hold the result if you wrap it in a
function (I suspect this is similar to the decorator suggestion,
just more explicit...
Pseudo code
tvar = None
def lev2(t):
global tvar
tvar = level2(t)
return tvar
tree = [ (top, tvar) for top in tops if lev2(top) ]
Is that any better than the loop? I'm not sure it is...
unless you have to build the list in multiple places.
Do I like relying on side effects of functions? No.
HTH,
Alan G.
More information about the Tutor
mailing list