Created
April 20, 2021 17:13
-
-
Save kerenskybr/0e7ebe18be16c57125e9e981603b5cea to your computer and use it in GitHub Desktop.
Grouping similar substrings in list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import groupby | |
test_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] | |
test_list.sort() | |
res = [list(i) for j, i in groupby(test_list, | |
lambda a: a.split('_')[0])] | |
#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’]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment