Temporary variables in list comprehensions
Paul Rubin
no.email at nospam.invalid
Mon Jan 9 05:44:12 EST 2017
Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
> [(expensive_calculation(x), expensive_calculation(x) + 1) for x in data]
def memoize(f):
cache = {}
def m(x):
if x in cache:
return cache[x]
a = f(x)
cache[x] = a
return a
return m
ec = memoize(expensive_calculation)
... [(ec(x), ec(x) + 1) for x in data]
Or can write:
@memoize
def expensive_calculation(x): ....
Note the Haskell version of your listcomp would be:
[(e, e+1) | x <- data_, let e = expensive_calculation x]
Maybe Python could get some version of that. I've wanted it more than
once. (I used "data_" because data is a Haskell keyword).
More information about the Python-list
mailing list