【问题标题】:Get top 5 max reoccurring values in a Python list? [duplicate]获取 Python 列表中的前 5 个最大重复值? [复制]
【发布时间】:2019-03-25 08:51:13
【问题描述】:

假设我有一个这样的列表:

list = [0,0,1,1,1,1,1,1,1,1,3,3,3,3,5,9,9,9,9,9,9,22,22,22,22,22,22,22,22,22,22,45]

前 5 个重复出现的值是: 22、1、9、3 和 0。

获取这些值的最佳方法是什么,以及它们重复出现的次数?我正在考虑将这些值推送到一个新列表中,这样我就会得到类似的东西:

new_list = [22,10, 1,8, 9,6, 3,4, 0,2]

列表值为奇数索引条目,重复出现的值为偶数索引条目。

编辑:不使用库的最简单方法是什么?

【问题讨论】:

  • 使用来自Collections 模块的Counter
  • 这些值是否已排序?请参阅collections.Counteritertools.groupby
  • 值已经排序。 collections.Counter 有效,但我想知道如何在不使用外部库的情况下做到这一点(主要是我自己函数中的代码)。

标签: python arrays list sorting


【解决方案1】:

使用标准库中的collections.Counter

import collections

list = [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 5, 9, 9, 9, 9, 9, 9, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 45]
ctr = collections.Counter(list)
print(ctr.most_common(5))

输出

[
    (22, 10),
    (1, 8),
    (9, 6),
    (3, 4),
    (0, 2),
]

【讨论】:

    【解决方案2】:

    使用集合。计数器:

    from collections import Counter
    
    
    l = [0,0,1,1,1,1,1,1,1,1,3,3,3,3,5,9,9,9,9,9,9,22,22,22,22,22,22,22,22,22,22,45]
    
    print(Counter(l).most_common())
    
    [(22, 10), (1, 8), (9, 6), (3, 4), (0, 2), (5, 1), (45, 1)]
    

    你给它一个可迭代的,它会为你计算。结果字典的键是被计数的值,它的值是它出现的频率。 (即 22 被计数 10 次)

    独库:collections.Counter(iterable)


    旁注:

    不要在类型或内置函数之后调用变量,你会隐藏它们并在以后遇到问题。永远不要打电话

    list, tuple, dict, set, max, min, abs, ... 
    

    见:https://docs.python.org/3/library/functions.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2023-03-30
      • 2022-11-30
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      相关资源
      最近更新 更多