Given the function that takes x and manipulate x as such:
>>> x = [5,3,0,0]
>>> j = 1
>>> for 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 a function:
def f(x):
j = 1
for i, xi in enumerate(x):
if xi == 0:
x[i] = 1.0/2**j
j+=1
return x
I want to change it into a lambda function but how is that possible when it uses an extra variable that not in my loop?
Without the complication of j+=1 and considering j as a constant I could do this:
j = 1
f = lambda x: [1.0/2**j if xi == 0 else xi for i, xi in enumerate(x)]
But I need the j to change when it if statement is made. How can that be achieved in a lambda function?
lambdafor this? What advantages do you feel that gives you? Alambdais nothing more than limited method of creating a function object in an expression.orexpressions. Readabilitywill be severely compromised.x.