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

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

    You can do this with lambda, which is more flexible than functools.partial():

    pow_two = lambda base: pow(base, 2)
    print(pow_two(3))  # 9
    

    More generally:

    def bind_skip_first(func, *args, **kwargs):
      return lambda first: func(first, *args, **kwargs)
    
    pow_two = bind_skip_first(pow, 2)
    print(pow_two(3))  # 9
    

    One down-side of lambda is that some libraries are not able to serialize it.

提交回复
热议问题