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

标签 python object copy shared deep-copy

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

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

#!/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 时,我发现 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):
        ...

...

关于Python 另一个字典中的两个字典另一个字典中的两个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660893/

相关文章:

python psycopg2 - ProgrammingError : function crosstab(unknown, 未知)不存在

python - Django:如何让 datetime 对象知道创建它的时区?

python - pinax-theme-bootstrap 无法加载 bootstrap

javascript - 不循环地从对象中删除某些属性

java - 这是什么意思 : ((Wrench)wrench). printInfo();

javascript - 尝试使用 Javascript 将字符串转换为对象,但在 ie8 中出现语法错误

c# - 有没有一种可移植的方法可以在 C# 中复制一 block 内存?

c - Windows 复制命令如 XCOPY、COPY、ROBOCOPY 在 System() 中的 C 语言中不起作用

c - 使用 unix 函数在 OSX 下移动/复制文件

python - 模板中的 Django substr/substring