具有Lambda值的字典更新所有条目 [英] Dictionary With Lambda Values Updates All Entries

查看:80
本文介绍了具有Lambda值的字典更新所有条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python 2.7.我有两个班级和一个namedtuple.一个类将字典作为实例属性和分配给该字典的函数存储. (这是这种情况的非常简化的版本). namedtuple很简单.另一类是通过add_to_test_dict函数调用将条目添加到test_dict的类.

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 very simplified version of the situation). The namedtuple is simple enough. The other class is one that adds entries into test_dict via the add_to_test_dict function call.

然后我实例化DictManipulator并调用test函数:

Then I instantiate DictManipulator and call the test function:

from collections import namedtuple


class DictHolder(object):
    def __init__(self):
        self.test_dict = {}
    def add_to_test_dict(self, key, val):
        self.test_dict[key] = val

TestTuple = namedtuple('TestTuple', 'name data')

class DictManipulator(object):
    def test(self):
        named_tuple_list = [TestTuple(name='key1', data=1), TestTuple(name='key2', data=1000)]
        self.my_dh = DictHolder()
        for item in named_tuple_list:
            self.my_dh.add_to_test_dict(item.name, lambda: item.data)

my_dm = DictManipulator()
my_dm.test()
print('key1 value: ', my_dm.my_dh.test_dict['key1']())
print('key2 value: ', my_dm.my_dh.test_dict['key2']())
# ('key1 value: ', 1000)
# ('key2 value: ', 1000)

为什么两个键在那里都返回相同的值?我已经做过足够的实验,可以说原始的named_tuple_list没有更新,并且我尝试使用lambda: copy.deepcopy(item.data),但这也不起作用.谢谢大家.

Why do both keys return the same value there? I have experimented enough to say that the original named_tuple_list is not updated, and I've tried to use lambda: copy.deepcopy(item.data), but that doesn't work either. Thanks very much, folks.

推荐答案

这是一个典型的后期绑定问题(请参见

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.

类似(可能重复)的问题: Python Lambda处于循环中

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

这篇关于具有Lambda值的字典更新所有条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆