【问题标题】:how to find most frequent values in a list?如何在列表中找到最常见的值?
【发布时间】:2021-09-22 09:43:09
【问题描述】:

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

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

【问题讨论】:

  • Counter 类从何而来?
  • 如果您省略most_common 的参数,它将返回所有 个计数的排序列表。这可能是最好的事情。您需要决定要使用多少个条目。
  • @jemand771 它是collections 的一部分,collections 是一个标准 Python 库。

标签: python arrays list sorting


【解决方案1】:

只需在most_common中取其中两个:

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

【讨论】:

  • 如果我想使用 2 我想获得 2 个不同的频率。我的意思是期望的输出应该是:[('138885662', 3), ('144024400', 3) ,('192562407', 2)]
  • @saharrezazadeh,那你能改变你的愿望输出吗?因为这完全符合您的要求:)
【解决方案2】:

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

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

【讨论】:

  • 您可能应该使用一个集合来避免在输出列表中出现重复项。要么将lst 设为一组,要么将for i in set(lastNodes): 设为
【解决方案3】:

使用迭代工具:

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)]

【讨论】:

    猜你喜欢
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2017-04-21
    • 2012-08-31
    • 2021-03-07
    • 2011-04-05
    相关资源
    最近更新 更多