python - map with lambda vs map with function - how to pass more than one variable to function? -


i wanted learn using map in python , google search brought me http://www.bogotobogo.com/python/python_fncs_map_filter_reduce.php have found helpful.

one of codes on page uses loop , puts map within loop in interesting way, , list used within map function takes list of 2 functions. here code:

def square(x):      return (x**2)  def cube(x):     return (x**3)  funcs = [square, cube]  r in range(5):     value = map(lambda x: x(r), funcs)     print value 

output:

[0, 0] [1, 1] [4, 8] [9, 27] [16, 64] 

so, @ point in tutorial, thought "well if can write code function on fly (lambda), written using standard function using def". changed code this:

def square(x):      return (x**2)  def cube(x):     return (x**3)  def test(x):     return x(r)  funcs = [square, cube]  r in range(5):     value = map(test, funcs)     print value 

i got same output first piece of code, bothered me variable r taken global namespace , code not tight functional programming. , there got tripped up. here code:

def square(x):      return (x**2)  def cube(x):     return (x**3)  def power(x):     return x(r)  def main():     funcs = [square, cube]     r in range(5):         value = map(power, funcs)         print value  if __name__ == "__main__":     main() 

i have played around code, issue passing function def power(x). have tried numerous ways of trying pass function, lambda has ability automatically assign x variable each iteration of list funcs.

is there way using standard def function, or not possible , lambda can used? since learning python , first language, trying understand what's going on here.

you nest power() function in main() function:

def main():     def power(x):         return x(r)      funcs = [square, cube]     r in range(5):         value = map(power, funcs)         print value 

so r taken surrounding scope again, not global. instead closure variable instead.

however, using lambda way inject r surrounding scope here , passing power() function:

def power(r, x):     return x(r)  def main():     funcs = [square, cube]     r in range(5):         value = map(lambda x: power(r, x), funcs)         print value 

here r still non-local, taken parent scope!

you create lambda r being default value second argument:

def power(r, x):     return x(r)  def main():     funcs = [square, cube]     r in range(5):         value = map(lambda x, r=r: power(r, x), funcs)         print value 

now r passed in default value instead, taken local. purposes of map() doesn't make difference here.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -