0

I have a problem, to sort the python list based on occurrence of elements.

for example:

#input list: 
l = [5,5,5,2,2,4,4,4,4,1]

#output list 
[4, 4, 4, 4, 5, 5, 5, 2, 2, 1]

I am able to solve the problem but i have used 3 loops, can anybody help me to do this in some pythonic way using a single loop. if you want i can share my solution. Thanks

Chandella07
  • 2,089
  • 14
  • 22

1 Answers1

4

You could use collections.Counter to count elements, then sort by that

>>> from collections import Counter
>>> l = [5,5,5,2,2,4,4,4,4,1]
>>> c = Counter(l)
>>> sorted(l, key=lambda i: c[i], reverse=True)
[4, 4, 4, 4, 5, 5, 5, 2, 2, 1]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • No need to import collections.Counter : `sorted(l, key = lambda x: l.count(x), reverse=True)` – May.D Jun 28 '21 at 12:16
  • 2
    @May.D Repeated calls to `list.count` are terrible. It is much better to collect all counts in one iteration. – user2390182 Jun 28 '21 at 12:16