python - What is the best way to create a function with a single argument from a function with multiple arguments? -
in python, have function f(x,y) defined as
def f(x,y): homecoming x + y now want define function g(x) = f(x,y) fixed value of y, determined @ run-time. in specific case, loop on several values of y, , need generate function g(x) each iteration:
for y in range(0,10): def g(x): homecoming f(x,y) #do g(x)... the above code works, question if there exists more efficient way this? seems me creating function object @ each loop iteration become inefficient in terms of memory/computation time.
use functools.partial:
>>> def f(x, y): homecoming x * y >>> functools import partial >>> g = partial(f, y=2) >>> g(3) 6 python
No comments:
Post a Comment