Can one partially apply the second argument of a function that takes no keyword arguments?

前端 未结 10 1557
太阳男子
太阳男子 2020-11-28 06:45

Take for example the python built in pow() function.

xs = [1,2,3,4,5,6,7,8]

from functools import partial

list(map(partial(pow,2),xs))

>&g         


        
相关标签:
10条回答
  • 2020-11-28 07:37

    Why not just create a quick lambda function which reorders the args and partial that

    partial(lambda p, x: pow(x, p), 2)
    
    0 讨论(0)
  • 2020-11-28 07:42

    If you can't use lambda functions, you can also write a simple wrapper function that reorders the arguments.

    def _pow(y, x):
        return pow(x, y)
    

    and then call

    list(map(partial(_pow,2),xs))
    
    >>> [1, 4, 9, 16, 25, 36, 49, 64]
    
    0 讨论(0)
  • 2020-11-28 07:45

    you could use a closure

    xs = [1,2,3,4,5,6,7,8]
    
    def closure(method, param):
      def t(x):
        return method(x, param)
      return t
    
    f = closure(pow, 2)
    f(10)
    f = closure(pow, 3)
    f(10)
    
    0 讨论(0)
  • 2020-11-28 07:47

    One way of doing it would be:

    def testfunc1(xs):
        from functools import partial
        def mypow(x,y): return x ** y
        return list(map(partial(mypow,y=2),xs))
    

    but this involves re-defining the pow function.

    if the use of partial was not 'needed' then a simple lambda would do the trick

    def testfunc2(xs):
        return list(map(lambda x: pow(x,2), xs))
    

    And a specific way to map the pow of 2 would be

    def testfunc5(xs):
        from operator import mul
        return list(map(mul,xs,xs))
    

    but none of these fully address the problem directly of partial applicaton in relation to keyword arguments

    0 讨论(0)
提交回复
热议问题