How to generate a list of different lambda functions with list comprehension?

前端 未结 4 446
有刺的猬
有刺的猬 2021-01-13 23:00

This question is distilled from the original application involving callback functions for Tkinter buttons. This is one line that illustrates the behavior.

lam

4条回答
  •  执笔经年
    2021-01-13 23:21

    You can use functools.partial to create specialized functions from a more general one by partial application, which reduces the parameter count by one:

    from functools import partial
    lambdas = [partial(lambda x: x, i) for i in range(3)]
    

    Here, lambda x: x is the general identity function taking one argument, and you create three specializations of it, taking no arguments, and returning fixed values.

提交回复
热议问题