Python另一个词典中的两个词典



我正在尝试创建一个结构,它可以很好地解析日志文件。我第一次尝试将字典设置为类对象,但这不起作用,因为我将它们设置为类属性。

我现在正在尝试以下方法来设置我的结构:

#!/usr/bin/python
class Test:
    def __init__(self):
        __tBin = {'80':0, '70':0, '60':0, '50':0,'40':0}
        __pBin = {}
        __results = list()
        info = {'tBin'   : __tBin.copy(),
                'pBin'   : __pBin.copy(),
                'results': __results}
        self.writeBuffer = list()
        self.errorBuffer = list()
        self.__tests = {'test1' : info.copy(),
                        'test2' : info.copy(),
                        'test3' : info.copy()}
    def test(self):
        self.__tests['test1']['tBin']['80'] += 1
        self.__tests['test2']['tBin']['80'] += 1
        self.__tests['test3']['tBin']['80'] += 1
        print "test1: " + str(self.__tests['test1']['tBin']['80'])
        print "test2: " + str(self.__tests['test2']['tBin']['80'])
        print "test3: " + str(self.__tests['test3']['tBin']['80'])
Test().test()

我在这里的目标是创建两个字典对象(__tBin和__pBin),并为每个测试制作它们的副本(即test1-test2-test3…)。然而,当我觉得自己在明确地复制它们时,我发现test1、test2和test3仍然共享相同的值。上面的代码还包括我如何测试我试图实现的目标。

虽然我希望看到1,1,1打印出来,但我看到了3,3,3并且我不明白为什么,尤其是当我在字典上显式地执行"copy()"时。

我使用的是Python 2.7.4

对于嵌套的数据结构,您需要进行深度复制,而不是浅层复制。请参见此处:http://docs.python.org/2/library/copy.html

导入文件开头的模块copy。然后用copy.deepcopy(info)替换类似info.copy()的调用。像这样:

#!/usr/bin/python
import copy
class Test:
    def __init__(self):
        ...
        info = {'tBin'   : __tBin.copy(),
                'pBin'   : __pBin.copy(),
                'results': __results}
        ...
        self.__tests = {'test1' : copy.deepcopy(info),
                        'test2' : copy.deepcopy(info),
                        'test3' : copy.deepcopy(info)}
    def test(self):
        ...
...

在中

self.__tests = {'test1' : info.copy(),
                    'test2' : info.copy(),
                    'test3' : info.copy()}

变量CCD_ 4仅由浅拷贝(即非递归拷贝)拷贝。如果你想复制__tBin和朋友,你应该在这里使用copy.deepcopy

相关内容

最新更新