Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let’s discuss certain way in which this problem can be performed.
Method : Using groupby()
+ list comprehension + lambda
This task can be performed using combination of above functions. In this, we group the elements using groupby() and decision of grouping element logic is done in form of lambda function.
# Python3 code to demonstrate working of # Group strings at particular element in list # using groupby() + list comprehension + lambda from itertools import groupby # initialize lists test_list = [ 'gfg' , 'is' , 'best' , 'and' , 'is' , 'popular' ] # printing original list print ( "The original list is : " + str (test_list)) # initialize partition element ele = 'is' # Group strings at particular element in list # using groupby() + list comprehension + lambda res = [ list (j) for i, j in groupby(test_list, lambda x:x = = ele) if not i] # printing result print ( "Resultant list after grouping : " + str (res)) |
The original list is : ['gfg', 'is', 'best', 'and', 'is', 'popular'] Resultant list after grouping : [['gfg'], ['best', 'and'], ['popular']]
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.