簡體   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