其他分享
首页 > 其他分享> > 在循环定义的字典上使用`==`运算符

在循环定义的字典上使用`==`运算符

作者:互联网

Python允许将字典与==进行比较

import copy

child = {'name': 'child'}
parent_1 = {'name': 'parent', 'child': child}
parent_2 = copy.deepcopy(parent_1)
print(parent_1 == parent_2)

如您所愿,打印True.

Python还允许字典相互循环引用.

child = {'name': 'child'}
parent_1 = {'name': 'parent', 'child': child}
child['parent'] = parent_1  # Create the circular reference

但是,尝试在具有循环引用的字典上使用==运算符会产生错误.

parent_2 = copy.deepcopy(parent_1)
print(parent_1 == parent_2)

退货

C:\Python34\python.exe -i C:/Users/anon/.PyCharm40/config/scratches/scratch_5
Traceback (most recent call last):
  File "C:/Users/anon/.PyCharm40/config/scratches/scratch_5", line 11, in <module>
    print(parent_1 == parent_2)
RuntimeError: maximum recursion depth exceeded in comparison

如何检查带有循环引用的两个字典是否相等?

解决方法:

您需要定义相等的含义.通常,字典的“相等”表示“所有键/值对都是“相等””.如果字典引用了它自己,则equal的定义可能会导致递归定义,即a == b且a == b.

举一个简单的例子:

a = {}; a['item'] = a
b = {}; b['item'] = b

a和b相等吗?为了知道这一点,您需要首先知道a和b是否相等…

您可以创建一个特殊的等式,如下所示:

def equal(a, b, special=[]):
    if not isinstance(a, dict) or not isinstance(b, dict):
        return a == b

    special = special + [a, b]
    set_keys = set(a.keys())
    if set_keys != set(b.keys()):
        return False

    for key in set_keys:
        if any(a[key] is i for i in special):
            continue
        elif any(b[key] is i for i in special):
            continue
        elif not equal(a[key], b[key], special):
            return False
    return True

标签:circular-reference,python-3-x,dictionary,python
来源: https://codeday.me/bug/20191120/2040682.html