Python 2.x gotchas and landmines

后端 未结 23 2271
北恋
北恋 2020-11-28 17:47

The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things sp

23条回答
  •  情深已故
    2020-11-28 18:29

    Loops and lambdas (or any closure, really): variables are bound by name

    funcs = []
    for x in range(5):
      funcs.append(lambda: x)
    
    [f() for f in funcs]
    # output:
    # 4 4 4 4 4
    

    A work around is either creating a separate function or passing the args by name:

    funcs = []
    for x in range(5):
      funcs.append(lambda x=x: x)
    [f() for f in funcs]
    # output:
    # 0 1 2 3 4
    

提交回复
热议问题