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

前端 未结 10 1632
太阳男子
太阳男子 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: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

提交回复
热议问题