如何在列表中查找最常见的值?

2024-10-02 04:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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)]

当然,这是一个示例列表。我有一个生成动态列表的算法。所以我不知道每个列表中有多少最常见的值


Tags: fromimport算法示例most列表counter动态
3条回答

您可以做的是在列表中循环并使用count函数,如果该元素的出现次数为3,则将其附加到另一个列表并

lst = []
for i in lastNodes:
    if lastNodes.count(i) == 3:
        lst.append(i)```

使用itertools:

from itertools import chain, islice, groupby
from operator import itemgetter

n = 2

# group the items having same count together
grouped = (list(group) for _, group in groupby(c.most_common(), key=itemgetter(1)))

# slice first `n` of them
top_n = islice(grouped, n)

# flatten
result = list(chain.from_iterable(top_n))

其中itemgetter(1)有助于根据计数器项的频率对其进行分组(在元组中,第0项是项本身,第1项是其计数,因此我们使用1;还注意groupby需要most_common提供的排序数据)

运行示例:

# for n = 1
[("138885662", 3), ("144024400", 3)]

# for n = 2
[("138885662", 3), ("144024400", 3), ("192562407", 2)]

# for n = 3
[("138885662", 3), ("144024400", 3), ("192562407", 2), ("121332964", 1), ("185592680", 1)]

只需在most_common中取两个:

>>> c.most_common(2)
[('138885662', 3), ('144024400', 3)]

相关问题 更多 >

    热门问题