我在列表中有一个字典,有些字典是相同的。我想找到重复的,并想要添加到新的列表或字典与他们有多少重复。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