collections.Counter: most_common INCLUDING equal counts

后端 未结 2 1520
南旧
南旧 2021-01-13 03:48

In collections.Counter, the method most_common(n) returns only the n most frequent items in a list. I need exactly that but I need to include the e

2条回答
  •  悲哀的现实
    2021-01-13 04:44

    You can do something like this:

    from itertools import takewhile
    
    def get_items_upto_count(dct, n):
      data = dct.most_common()
      val = data[n-1][1] #get the value of n-1th item
      #Now collect all items whose value is greater than or equal to `val`.
      return list(takewhile(lambda x: x[1] >= val, data))
    
    test = Counter(["A","A","A","B","B","C","C","D","D","E","F","G","H"])
    
    print get_items_upto_count(test, 2)
    #[('A', 3), ('C', 2), ('B', 2), ('D', 2)]
    

提交回复
热议问题