Python | Group and count similar records



Method # 1: Using a loop + Counter () + set ()
A combination of the above functionality can be used to achieve this goal. In this we run a loop to grab each tuple and add it to the set and check if it already exists, then increment and add the counter value to it. The cumulative score is achieved using Counter () .

# Python3 code to demonstrate how it works
# Group and read similar posts
# using Counter () + loop + set ()

from collections import Counter

 
# initialize the list

test_list = [( `gfg` ,), ( `is` ,), ( `best` ,), ( ` gfg` ,),

  ( `is` ,), ( ` for` ,), ( `geeks` ,)]

  
# print original list

print ( " The original list: " + str (test_list))

 
# Group and read similar posts
# using Counter () + loop + set ()

res = []

temp = set ()

counter = Counter (test_list)

for sub in test_list:

  if sub not in temp:

res. append ((counter [sub],) + sub)

temp.add (sub)

 
# print result

print ( "Grouped and counted list is: " + str (res))

Output:

The original list: [(` gfg `,), (` is`,), (`best`,), (`gfg`,), (`is`,), (` for `,), (` geeks`,)]
Grouped and counted list is: [(2, `gfg`), (2, `is`), (1, `best`), (1, `for`), (1, `geeks`)]

Method # 2: Using Counter () + list comprehension + items ()

This is one liner approach and recommended for programming. The looping task is handled through a list comprehension, and items () is used to access all the elements of the Counter-converted dictionary, allowing computations to be performed.

# Python3 code for demonstrations
# Group and read similar posts
# using Counter () + list comprehension + items ()

from collections import Counter

 
# initialize the list

test_list = [( `gfg` ,), ( ` is` ,), ( ` best` ,), ( `gfg` ,),

  ( `is` ,), ( ` for` ,), ( `geeks` ,)]

 
# print original list

print ( " The original list: " + str (test_list))

 
# Group and count similar posts
# using Counter () + list comprehension + items ()

res = [(counter,) + ele for ele, counter in Counter (test_list) .items ()]

 
# print result

print ( "Grouped and counted list is:" + str (res))

Output:

The original list: [(`gfg`,), (`is`,), (`best`,), (`gfg`,), (`is`,), (`for`,) , (`geeks`,)]
Grouped and counted list is: [(2, `gfg`), (2, `is`), (1, `best`), (1, `for`) , (1, `geeks`)]