我想使用collections.Counter
在列表中查找频繁值。下面是一个示例列表:
from collections import Counter
lastNodes = ['138885662','192562407','192562407','138885662','121332964','185592680','144024400','144024400','144024400','138885662']
c = Counter(lastNodes)
print(c)
的输出:
Counter({'121332964': 1,
'138885662': 3,
'144024400': 3,
'185592680': 1,
'192562407': 2})
我使用c.most_common(1)
获取最频繁的值,该值输出[('138885662', 3)]
但是我想得到列表中重复了3次的值。期望输出:
[('138885662', 3), ('144024400', 3)]
如果我想要那些有3和2个重复值的值:
[('138885662', 3), ('144024400', 3), ('192562407', 2)]
当然,这是一个示例列表。我有一个生成动态列表的算法。所以我不知道每个列表中有多少最常见的值
您可以做的是在列表中循环并使用count函数,如果该元素的出现次数为3,则将其附加到另一个列表并
使用itertools:
其中
itemgetter(1)
有助于根据计数器项的频率对其进行分组(在元组中,第0项是项本身,第1项是其计数,因此我们使用1;还注意groupby
需要most_common
提供的排序数据)运行示例:
只需在
most_common
中取两个:相关问题 更多 >
编程相关推荐