Python | Sort list items by frequency



Method # 1: Using collections.counter()

# Python code for demo
# sort the list by frequency
number of items

 

from collections import Counter

 

ini_list = [ 1 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 , 7

1 , 1 , 2 , 4 , 7 , 8 , 9 , 6 , 6 , 6 ]

  
# print the initial ini_lis t

print ( "initial list" , str (ini_list))

 
# sort by element frequency byte

result = [item for items, c in Counter (ini_list) .most_common ()

for item in [items] * c]

 
# print the final result

pr int ( "final list" , str (result))

Exit :

initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 5, 7, 1, 1, 2 , 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4, 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]

Method # 2: Using iterations

# Python code for demo
# sort the list by frequency
number of elements

 

from collections import Counter

from itertools import repeat, chain

 

ini_list = [ 1 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 , 7 ,

1 , 1 , 2 , 4 , 7 , 8 , 9 , 6 , 6 , 6 ]

 
# print the initial ini_list

print ( "initial list" , str (ini_list))

  
# sorting by element frequency byte

result = list (chain.from_iterable (repeat (i, c)

for i, c in Counter (ini_list) .most_common ()))

 
# print the final result

print ( "final list" , str (result))

Exit:

initial list [1, 2, 3, 4, 4, 5, 5, 5, 5, 7, 1, 1, 2, 4, 7, 8, 9, 6, 6, 6]
final list [5, 5, 5, 5, 1, 1, 1, 4 , 4, 4, 6, 6, 6, 2, 2, 7, 7, 3, 8, 9]

Method # 3: Usage sorted

# Python code for demo
# sort the list by frequency
amount elements

 

from collections import Counter

  

ini_list = [ 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 ,

5 , 5 , 5 , 4 , 4 , 4 , 4 , 4 , 4 ]

 
# print the initial ini_list

print ( "initial list" , str (ini_list))

  
# sort by element frequency byte

result = sorted (ini_list, key = ini_list.count,

  reverse = True )

 
# print the final result

print ( "final list" , str (result))

Exit:

initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]
final list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]