【问题标题】:Python Two Dictionaries within another Dictionary within another DictionaryPython 另一个字典中的另一个字典中的两个字典
【发布时间】:2013-07-15 18:08:46
【问题描述】:

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

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

#!/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

【问题讨论】:

  • 如果你解析xml或者html,我推荐lxml和etree。

标签: python object copy shared deep-copy


【解决方案1】:

对于嵌套数据结构,您需要制作深拷贝而不是浅拷贝。 见这里: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):
        ...

...

【讨论】:

  • 我明白了,谢谢。所以我们在填充 info dict 时不需要深拷贝的原因是因为 __tBin 或 __pBin 不包含更多对象,而 info dict 包含,因此我们需要进行递归复制,对吧?
  • 是的。但是请记住,简单的深层副本并不总是您想要的。例如,如果对象中有实例变量指向不应复制的对象,则您不想递归地复制它们。我提供的链接提供了其他信息,这些信息可能有助于更深入地了解整个问题。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多