Skip to content
Related Articles

Related Articles

Python | Identical Strings Grouping
  • Last Updated : 19 Feb, 2020

Sometimes, we need to perform the conventional task of grouping some like Strings to a separate list and thus forming a list of list. This can also helps in counting and also get the sorted order of elements. Let’s discuss certain ways in which this can be done.

Method #1 : Using collections.Counter()
This particular function can prove to be quite useful to perform this particular task as it counts the frequency of Strings in list and then we can pair them using the list comprehension.




# Python3 code to demonstrate
# Identical Strings Grouping 
# using collections.Counter()
import collections
  
# initializing list 
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using collections.Counter()
# Identical Strings Grouping
temp = collections.Counter(test_list)
res = [[i] * j for i, j in temp.items()]
  
# print result
print("The Strings after grouping are : " + str(res))
Output :
The original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['best', 'best', 'best'], ['Gfg', 'Gfg', 'Gfg'], ['is', 'is']]

 

Method #2 : Using itertools.groupby()
This problem can easily solved by traditional groupby functionality that is offered by Python via groupby function, which groups the like elements as suggested by name.






# Python3 code to demonstrate
# Identical Strings Grouping
# using itertools.groupby()
import itertools
  
# initializing list 
test_list = ["Gfg", "best", "is", "Gfg", "is", "best", "Gfg", "best"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using itertools.groupby()
# Identical Strings Grouping
res = [list(i) for j, i in itertools.groupby(sorted(test_list))]
  
# print result
print("The Strings after grouping are : " + str(res))
Output :
The original list : ['Gfg', 'best', 'is', 'Gfg', 'is', 'best', 'Gfg', 'best']
The Strings after grouping are : [['best', 'best', 'best'], ['Gfg', 'Gfg', 'Gfg'], ['is', 'is']]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :