小编Ase*_*cus的帖子

仅存储更改的Python字典

我使用Inspyred库编写了一个用于设计优化的代码及其遗传算法的实现.本质上,优化过程在单个数据结构上创建了大量变体,在我的例子中,这是一个嵌套字典.

为了减少进程中使用的内存量,我一直在尝试创建某种差异字典类型,它只存储与基本字典不同的项目.其原因在于,在典型情况下,数据结构中95%的数据不会在任何变体中被修改,但数据结构的任何部分都可以包含变体.因此,出于灵活性的原因,我希望数据类型的行为或多或少像字典,但只存储更改.

这是我试图创建这个的结果:

#!/usr/bin/python

import unittest
import copy

global_base={}

class DifferentialDict(object):
    """
    dictionary with differential storage of changes
    all DifferentialDict objects have the same base dictionary
    """

    def __init__(self,base=None):
        global global_base

        self.changes={}

        if not base==None:
            self.set_base(base)

    def set_base(self,base):
        global global_base
        global_base=copy.deepcopy(base)

    def __copy__(self):
        return self

    def __deepcopy__(self):
        new=DifferentialDict()
        new.changes=copy.deepcopy(self.changes)
        return new

    def get(self):
        global global_base
        outdict=copy.deepcopy(global_base)
        for key in self.changes:
            outdict[key]=self.changes[key]
        return outdict

    def __setitem__(self,key,value):
        self.changes[key]=value

    def __getitem__(self,key):
        global global_base
        if key in self.changes:
            return self.changes[key]
        else:
            return global_base[key]

class …
Run Code Online (Sandbox Code Playgroud)

python dictionary nested

5
推荐指数
1
解决办法
140
查看次数

标签 统计

dictionary ×1

nested ×1

python ×1