How does a lambda function refer to its parameters in python?

前端 未结 4 1740
余生分开走
余生分开走 2021-01-05 17:09

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like

fs = [         


        
4条回答
  •  -上瘾入骨i
    2021-01-05 17:39

    i is local and there are indeed closures in python.

    I believe your confusion is that you assigh fs to a list of identical function.

    >>> fs = [lambda x: x + i for i in xrange(10)]
    >>> fs
    [ at 0x02C6E930>,  at 0x02C6E970>,  at 0x02C6E9B0>,  at 0x02C6E9F0>,  at 0x02C6EA30>,  at 0x02C6EA70>,  at 0x02C6EAB0>,  at 0x02C6EAF0>,  at 0x02C6EB30>,  at 0x02C6EB70>]
    >>> fs[0](0)
    9
    >>> fs[0](100)
    109
    >>> fs[5](0)
    9
    >>> fs[5](100)
    109
    

    I think a single function returning a list would be more appropriate.

    >>> fs3 = lambda x: [x + i for i in xrange(10)]
    >>> fs3
     at 0x02C6EC70>
    >>> fs3(0)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

提交回复
热议问题