从defaultdict提取重复值

时间:2019-06-04 10:47:26

标签: python list dictionary

我有一个defaultdict定义如下:

devicedict1=collections.defaultdict(list)

设备字典包含一个索引键和一个双精度值,如下所示:

{0: ['9085', '9084'], 1: ['9084', '5684'], 2: ['9084', '3707'], 3: ['9084', '3707'], 4: ['3707', '9084'], 5: ['9084', '3707'], 6: ['3707', '9084'], 7: ['9084', '5684'], 8: ['9084', '3707'], 9: ['9084', '3707'], 10: ['9084', '3707'], 11: ['9084', '5684'], 12: ['3707', '9084']

我想提取出现最多的元组(值,值)并打印它们。

我尝试使用Counter和items()。

e=Counter(devicedict1.items())
print(e)

但是它似乎不起作用。它应该给我们以下结果:

['9084', '3707']:30
['9084', '5684']:10

2 个答案:

答案 0 :(得分:1)

如果您将componentWillMount() { if(!this.props.isAuthenticated){ // redirect this.props.history.push('/login'); } } 中的值map用于元组,则可以使用Counter,因为与列表不同,元组是可哈希的。要获得显示最多的n元组,请使用most_common方法:

n = 3
Counter(map(tuple, devicedict1.values())).most_common(n)
# [(('9084', '3707'), 6), (('9084', '5684'), 3), (('3707', '9084'), n)]

答案 1 :(得分:0)

使用Counter

例如:

from collections import Counter

data = {0: ['9085', '9084'], 1: ['9084', '5684'], 2: ['9084', '3707'], 3: ['9084', '3707'], 4: ['3707', '9084'], 5: ['9084', '3707'], 6: ['3707', '9084'], 7: ['9084', '5684'], 8: ['9084', '3707'], 9: ['9084', '3707'], 10: ['9084', '3707'], 11: ['9084', '5684'], 12: ['3707', '9084']}
c = Counter(map(tuple, data.values()))
print(c.most_common(2))

输出:

[(('9084', '3707'), 6), (('9084', '5684'), 3)]
相关问题