Python | Group list items by frequency

Examples :

  Input:  [1, 3, 4, 4, 1, 5, 3, 1]  Output:  [(1, 3), (3, 2), (4, 2), (5, 1)]  Input:  [`x`,` a`, `x` , `y`,` a`, `x`]  Output:  [(` x`, 3), (`a`, 2), (` y`, 1)]  

Method # 1: Understanding a List

We can use lists to form tuples of each element and a counter of its occurrence and store it in & # 39; res & # 39; but it will contain a duplicate of the first element. So, to remove the duplicate first item, we use OrderedDict (res) .items () .

# Python3 program to the list groupings
# frequency-based elements

from collections import OrderedDict 

  

def group_list (lst):

 

res =   [(el, lst.count (el)) for el in lst]

  return list (OrderedDict (res) .items ( ))

 
# Driver code

lst = [ 1 , 3 , 4 , 4 , 1 , 5 , 3 , 1 ]

print (group_list (lst))

Exit:

 [(1, 3), (3, 2), (4, 2), ( 5, 1)] 

Spo int # 2: Using collections.Counter()

collections.Counter () provides two direct methods keys () and values ​​() which provide elements and their occurrences. Finally, zip them together using the Python zip () method.

# Python3 program into grouping list
# frequency-based elements

from collections import Counter

 

def group_list (lst):

  

return list ( zip (Counter (lst) .keys (), Counter (lst). values ​​()))

 
# Driver code lst = [ 1 , 3 , 4 , 4 , 1 , 5 , 3 , 1 ]

print (group_list (lst))

Exit:

 [(1, 3), (3, 2), (4, 2), (5 , 1)]