Professional Documents
Culture Documents
Python Grouping Similar Substrings in List - GeeksforGeeks
Python Grouping Similar Substrings in List - GeeksforGeeks
DSA Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java
Python3
1 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
# printing the original list
print ("The original list is : " + str(test_list))
# using lambda + itertools.groupby() + split()
# group similar substrings
res = [list(i) for j, i in groupby(test_list,
lambda a: a.split('_')[0])]
# printing result
print ("The grouped list is : " + str(res))
Output :
The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’]
The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’],
[‘pro_3’]]
Python3
2 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
# printing the original list
print ("The original list is : " + str(test_list))
# using lambda + itertools.groupby() + partition()
# group similar substrings
res = [list(i) for j, i in groupby(test_list,
lambda a: a.partition('_')[0])]
# printing result
print ("The grouped list is : " + str(res))
Output :
The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’]
The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’],
[‘pro_3’]]
Like 1
Previous Next
R ECO M M E N D E D A RT I C L E S Page : 1 2 3
▲
3 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
Article Contributed By :
manjeet_04
@manjeet_04
Improved By : sweetyty
4 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Load Comments
5 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
feedback@geeksforgeeks.org
Company Learn
About Us Algorithms
Courses
News Languages
Top News
Python
Technology
Java
Work & Career
CPP
Business
Golang
Finance
C#
Lifestyle
SQL
Knowledge
Kotlin
Bootstrap Internships
▲
ReactJS Video Internship
6 of 7 11/4/22, 21:02
Python | Grouping similar substrings in list - GeeksforGeeks https://www.geeksforgeeks.org/python-grouping-similar-sub...
7 of 7 11/4/22, 21:02