Skip to main content
 首页 » 编程设计

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

2024年11月01日8zhoujg

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

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

#!/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。然后将 info.copy() 之类的调用替换为 copy.deepcopy(info)。像这样:

#!/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): 
        ... 
 
...