-2

Let's say I have a list like so:

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]

The top 5 reoccurring values would be: 22, 1, 9, 3, and 0.

What is the best way to get these values, as well as the number of times they reoccur? I was thinking of pushing the values into a new list, so that I get something like:

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

With the list value being the odd index entry, and the reoccurred value being the even index entry.

EDIT: What is the simplest way to do this without using a library?

qbuffer
  • 315
  • 1
  • 11

2 Answers2

0

Use collections.Counter:

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

You feed it an iterable and it counts it for you. The resultings dictionaries key is the value that was counted, its value is how often it occured. (i.e. 22 was counted 10 times)

Doku: collections.Counter(iterable)


Sidenote:

dont call variables after types or built ins, you shadow them and get problems later. Never call anything

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

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

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
0

Use collections.Counter from the standard library.

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

outputs

[
    (22, 10),
    (1, 8),
    (9, 6),
    (3, 4),
    (0, 2),
]
AKX
  • 93,995
  • 11
  • 81
  • 98