我在列表中有一個字典,有些字典是相同的。我想找到重複的,並想要添加到新的列表或字典與他們有多少重複。Python在列表中找到重複的字典,並用計數將它們分開
import itertools
myListCombined = list()
for a, b in itertools.combinations(myList, 2):
is_equal = set(a.items()) - set(b.items())
if len(is_equal) == 0:
a.update(count=2)
myListCombined.append(a)
else:
a.update(count=1)
b.update(count=1)
myListCombined.append(a)
myListCombined.append(b)
myListCombined = [i for n, i enumerate(myListCombine) if i not in myListCombine[n + 1:]]
此代碼有點不錯,但它只是在列表中的2個重複的字典。 a.update(count = 2)在這種情況下不起作用。 我最後一行將它們分開後,也刪除了重複的字典,但我不確定它是否能正常工作。
輸入:
[{'name': 'Mary', 'age': 25, 'salary': 1000},
{'name': 'John', 'age': 25, 'salary': 2000},
{'name': 'George', 'age': 30, 'salary': 2500},
{'name': 'John', 'age': 25, 'salary': 2000},
{'name': 'John', 'age': 25, 'salary': 2000}]
所需的輸出:
[{'name': 'Mary', 'age': 25, 'salary': 1000, 'count':1},
{'name': 'John', 'age': 25, 'salary': 2000, 'count': 3},
{'name': 'George', 'age': 30, 'salary': 2500, 'count' 1}]
請發表您的輸入和期望的輸出。 – Ajax1234
編輯,謝謝@ Ajax1234 –
請在下面看到我的回覆。 – Ajax1234