4 回答

TA貢獻1846條經驗 獲得超7個贊
您可以使用frozenset()將每個字典散列items()到字典中,然后簡單地獲取分配的值:
list({frozenset(x.items()): x for x in list1 + list2}.values())
或使用map()應用于集合理解:
list(map(dict, {frozenset(x.items()) for x in list1 + list2}))
甚至只使用列表理解:
[dict(d) for d in {frozenset(x.items()) for x in list1 + list2}]
這將產生無序的結果:
[{'doc': 1, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 1, 'pos_fin': 12, 'pos_ini': 7},
{'doc': 2, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 7, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 1, 'pos_fin': 7, 'pos_ini': 6},
{'doc': 2, 'pos_fin': 30, 'pos_ini': 25}]
注意:如果需要訂購,則可以collections.OrderedDict()在此處改用:
from collections import OrderedDict
list(OrderedDict((frozenset(x.items()), x) for x in list1 + list2).values())
給出以下有序結果:
[{'doc': 1, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 1, 'pos_fin': 12, 'pos_ini': 7},
{'doc': 2, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 7, 'pos_fin': 10, 'pos_ini': 5},
{'doc': 1, 'pos_fin': 7, 'pos_ini': 6},
{'doc': 2, 'pos_fin': 30, 'pos_ini': 25}]

TA貢獻1886條經驗 獲得超2個贊
在Python中,有個內置的set
集合對此非常適合。問題在于集合需要hashable
元素,因此您必須將字典轉換為元組集合:
[dict(items) for items in set(tuple(sorted(d.items())) for d in (list1 + list2))]

TA貢獻1860條經驗 獲得超8個贊
您可以根據這些值創建一個集合,而不是將其轉換為可哈希對象(如元組)的字典:
unique_list = set(tuple(dictionary.items())) for dictionary in list1 + list2)
然后可以再次轉換回字典和列表格式:
l = []
for item in unique_list:
l.append(dict(item))
像上面的東西應該工作。
添加回答
舉報