繁体   English   中英

删除dicts,lists,tuples中的循环引用

[英]Remove circular references in dicts, lists, tuples

我有以下真正的黑客代码,它从dicttuplelist对象构建的任何类型的数据结构中删除循环引用。

import ast

def remove_circular_refs(o):
    return ast.literal_eval(str(o).replace("{...}", 'None'))

但我不喜欢它有多酷。 这可以在不将数据结构转换为字符串表示的情况下完成吗?

这是一个用于测试的示例结构:

doc1 = {
    "key": "value",
    "type": "test1",
}
doc1["self"] = doc1
doc = {
    'tags': 'Stackoverflow python question',
    'type': 'Stackoverflow python question',
}
doc2 = {
    'value': 2,
    'id': 2,
}
remove_circular_refs(doc)
remove_circular_refs(doc1)
remove_circular_refs(doc2)

不要使用字符串转换,不。 只需通过遍历数据结构来检测引用:

def remove_circular_refs(ob, _seen=None):
    if _seen is None:
        _seen = set()
    if id(ob) in _seen:
        # circular reference, remove it.
        return None
    _seen.add(id(ob))
    res = ob
    if isinstance(ob, dict):
        res = {
            remove_circular_refs(k, _seen): remove_circular_refs(v, _seen)
            for k, v in ob.items()}
    elif isinstance(ob, (list, tuple, set, frozenset)):
        res = type(ob)(remove_circular_refs(v, _seen) for v in ob)
    # remove id again; only *nested* references count
    _seen.remove(id(ob))
    return res

这包括dictlisttuplesetfrozenset对象; 它会记住每个看到的对象的id() ,当它再次被看到它时会被替换为None

演示:

>>> doc1 = {
...     "key": "value",
...     "type": "test1",
... }
>>> doc1["self"] = doc1
>>> doc1
{'key': 'value', 'type': 'test1', 'self': {...}}
>>> remove_circular_refs(doc1)
{'key': 'value', 'type': 'test1', 'self': None}
>>> doc2 = {
...     'foo': [],
... }
>>> doc2['foo'].append((doc2,))
>>> doc2
{'foo': [({...},)]}
>>> remove_circular_refs(doc2)
{'foo': [(None,)]}
>>> doc3 = {
...     'foo': 'string 1', 'bar': 'string 1',
...     'ham': 1, 'spam': 1
... }
>>> remove_circular_refs(doc3)
{'foo': 'string 1', 'bar': 'string 1', 'ham': 1, 'spam': 1}

对于doc3 ,最后一个测试包含共享引用; 'string 1'1在内存中只存在一次 ,字典包含对这些对象的多个引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM