python - Lambda-ize functions that uses variables outside of the function -


given function takes x , manipulate x such:

>>> x = [5,3,0,0] >>> j = 1 >>> i, xi in enumerate(x): ...     if xi == 0: ...             x[i] = 1.0/2**j ...             j+=1 ...  >>> x [5, 3, 0.5, 0.25] 

and in function:

def f(x):   j = 1   i, xi in enumerate(x):     if xi == 0:       x[i] = 1.0/2**j       j+=1   return x 

i want change lambda function how possible when uses variable not in loop?

without complication of j+=1 , considering j constant this:

j = 1 f = lambda x: [1.0/2**j if xi == 0 else xi i, xi in enumerate(x)] 

but need j change when if statement made. how can achieved in lambda function?

you make j itertools.count() object; each time call next() on it'll yield next value in sequence:

from itertools import count  j = count(1) f = lambda x: [1.0 / 2 ** next(j) if xi == 0 else xi i, xi in enumerate(x)] 

this works because ever ask next value when x == 0 true.

however, need reset j each time want use lambda. incorporate list comprehension one-element tuple loop over:

f = lambda x: [1.0 / 2 ** next(j) if xi == 0 else xi                j in (count(1),)                i, xi in enumerate(x)] 

all not readable. i'd stick def function object instead.

as side note, use or replace .. if xi == 0 else xi expression; xi == 0 makes xi falsey:

f = lambda x: [xi or 1.0 / 2 ** next(j)                j in (count(1),)                i, xi in enumerate(x)] 

Comments