1 回答

TA貢獻1802條經驗 獲得超5個贊
這是一種通常應該有效的解決方案,即使列表具有同一字典的倍數,并且一個列表中的字典可以具有公共鍵也是如此。這個想法是將字典轉換為規范的、可散列的形式,然后使用Counter.
它確實假設字典鍵是可比較的并且字典值是可散列的,因此如果您的字典具有不可比較的鍵或不可散列的值,則它將不起作用。
from collections import Counter
def dict_to_canonical_hashable(d):
return tuple(sorted(d.items()))
def unordered_lists_equal(a, b):
canonical_a = Counter(map(dict_to_canonical_hashable, a))
canonical_b = Counter(map(dict_to_canonical_hashable, b))
return canonical_a == canonical_b
測試:
>>> unordered_lists_equal(dict_list_1, dict_list_2)
True
>>> unordered_lists_equal(dict_list_1, dict_list_3)
False
>>> unordered_lists_equal(dict_list_2, dict_list_3)
False
>>> unordered_lists_equal([{1: 2, 3: 4}, {5: 6}], [{1: 2}, {3: 4, 5: 6}])
False
>>> unordered_lists_equal([{1: 2}, {1: 3}], [{1: 3}, {1: 2}])
True
>>> unordered_lists_equal([{1: 2}, {1: 2}], [{1: 2}])
False
>>> unordered_lists_equal([{1: 2}, {1: 2}], [{1: 2}, {1: 2}])
True
添加回答
舉報