python中带过滤的深度复制

python中带过滤的深度复制,python,json,filter,deep-copy,Python,Json,Filter,Deep Copy,我想制作python数据结构的深层副本,根据一些标准忽略一些元素 例如,输入可以是任意的json,我想复制除带有“ignore”键的字典以外的所有内容。像这样: def my_filter(entry): # return true if we need to skip this entry if not isinstance(entry, dict): return False return ('ignore' in entry) a = [ {"free":

我想制作python数据结构的深层副本,根据一些标准忽略一些元素

例如,输入可以是任意的json,我想复制除带有“ignore”键的字典以外的所有内容。像这样:

def my_filter(entry):
    # return true if we need to skip this entry
    if not isinstance(entry, dict): return False
    return ('ignore' in entry)

a = [
    {"free": "yourself", "ignore": ""},
    [
        {"two": "words" },
        {"one": "finger"},
        [{"apples": 2}, {"array": [1,2,3,4], "ignore": ""}],
    ],
    {"hi": "there", "ignore": ""},
]

print copy_with_filter(a, my_filter)
它将输出

[[{'two': 'words'}, {'one': 'finger'}, [{'apples': 2}]]]
我已经实现了这段代码,它完成了json输入的工作,也就是说,只有list、dict或Literal可以出现,并且工作得很好:

def copy_with_filter(a, filter_func):
    # assume input is either list, or dict, or "literal" (i.e. string/int/float)
    if isinstance(a, list):
        out = [ copy_with_filter(x, filter_func) for x in a if not filter_func(x) ]
    elif isinstance(a, dict):
        out = a.copy() # shallow copy first
        for k in a.iterkeys():
            # replace values with filtered deep copies
            out[k] = copy_with_filter(a[k], filter_func)
    else:
        out = a
    return out

虽然我的问题是,是否有更通用/更好/内置的方式在python中使用过滤进行深度复制?

使用python deepcopy内置的Memorization-这在深度复制具有交叉引用资源的结构时效果更好-您的方法将创建多次引用的内容的副本在根对象的子对象中

有些糟糕的Python文档:

。。。但是有很好的教程。一篇关于重载自定义类的复制构造函数的文章:

添加过滤稍微复杂一点——但对于自定义对象来说,这很容易(只是在deepcopy构造函数的早期,没有向memo dict添加新对象——唯一真正的困难是自定义过滤规则中的管道,但这只是管道)