Dictionary With Lambda Values Updates All Entries

前端 未结 1 966
再見小時候
再見小時候 2020-12-07 04:15

I\'m in Python 2.7. I have two classes and one namedtuple. One class houses a dictionary as an instance attribute and a function that assigns to that dictionary. (This is a

相关标签:
1条回答
  • 2020-12-07 04:52

    This is a typical late binding issue (see common gotchas): when the functions (being lambda/anonymous has nothing to do with it) are called, they access the current value of item, which is the last one from the loop. Try

    lambda x=item: x.data 
    

    in your loop instead. This works since default arguments are bound to a function at definition time while common local variables are evaluated at calling time.

    Similar (possible duplicate) question: Python Lambda in a loop

    0 讨论(0)
提交回复
热议问题