python - python 中的深度复制和过滤

标签 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": "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 输入的工作,即仅可以存在列表、字典或文字时,并且效果很好:

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 内置函数 - 在深度复制具有交叉引用资源的结构时效果更好 - 您的方法将创建在根对象的子对象中多次引用的事物的重复项。

有点糟糕的 Python 文档:

https://docs.python.org/2/library/copy.html

...但是那里有很好的教程。一篇关于重载自定义类的复制构造函数的 SO 帖子:

Python: Implementation of shallow and deep copy constructors

添加过滤有点繁琐 - 但对于自定义对象来说,这很容易(只是在 deepcopy 构造函数中早期使用,而不需要向备忘录字典中添加新对象 - 唯一真正的困难是管道在自定义过滤规则中,但这只是管道)。

关于python - python 中的深度复制和过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863531/

相关文章:

python - 如何更改 matplotlib 图的默认窗口位置?

java - 尝试解析 JSON 数据时出现此错误 W/System.err : org. json.JSONException:对客户没有值(value)

ios - 使用 NSPredicate 搜索 - 全名

session - playframework 过滤器中的 Http.Context

python - 用于抓取所有评论和回复的 YouTube 数据 API

python - 如何修改自定义 Tensorflow 层中的图像? (提供工作示例)

json - 在 Play for Scala 中将异构列表与 Json 相互转换

javascript - 如何根据 Angular 给出的变量显示某些内容

python - 如何使用Snakemake中的expand函数对列表进行排列或组合

jquery - 无法从 yahoo 管道读取 json