【发布时间】:2016-07-15 13:38:33
【问题描述】:
我有一个包含多个 dicts 的列表,我需要检查哪些 dicts 重复并创建一个新列表,每个列表只出现一次,但第一个列表中重复元素的数量。
例如:
我有那个清单:
[{'a': 123, 'b': 1234, 'c': 'john', 'amount': 1},
{'a': 456, 'b': 1234, 'c': 'doe','amount': 1},
{'a': 456, 'b': 1234, 'c': 'steve','amount': 1},
{'a': 123, 'b': 1234, 'c': 'john','amount': 1},
{'a': 123, 'b': 1234, 'c': 'john','amount': 1}]
我需要输出:
[{'a': 123, 'b': 1234, 'c': 'john', 'amount': 3},
{'a': 456, 'b': 1234, 'c': 'steve','amount': 1},
{'a': 456, 'b': 1234, 'c': 'doe','amount': 1}]
我尝试了一些通过谷歌搜索找到的东西,但没有完全奏效,我尝试的最后一个让我知道重复的在哪里,但我不知道下一步该做什么。
def index(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
for i in l:
if len(index(l,i)) > 1:
i['amount'] += 1
print l
但它会返回
[{'a': 123, 'c': 'john', 'b': 1234, 'amount': 2},
{'a': 456, 'c': 'doe', 'b': 1234, 'amount': 1},
{'a': 456, 'c': 'steve', 'b': 1234, 'amount': 1},
{'a': 123, 'c': 'john', 'b': 1234, 'amount': 2},
{'a': 123, 'c': 'john', 'b': 1234, 'amount': 1}]
【问题讨论】:
-
你试过
collections.Counter吗? -
@Daenyth 是的,我做到了,但是因为它是一个 dicts 列表,所以它不起作用 TypeError: unhashable type: 'dict'
标签: python list dictionary count repeat