Group similar list items to sub-lists


Who can help me to find a way how to group my list values by A001, B001, C001 in this case and create sublists? The string structure XX-XXX-XXXX would be the same at all times.

On the right is the list I’m looking for.

an issue with Python

lst_header = IN[0]
lst_b = IN[1]
fun = lambda x, lsty : [ x ]+[y for y in lsty if y.endswith(x)]
OUT = [fun(x,lst_b) for x in lst_header]

or only with the full list XX-XXX-XXXX

full_list = IN[0]
set_header = set([(x.split('-'))[-1] for x in full_list if (x.split('-'))[-1]])
fun = lambda x, lsty : [x]+[y for y in lsty if y.endswith(x)]
OUT = [fun(x,full_list ) for x in set_header]

you can do something like this

1 Like

Look good. Thanks! But quite hard to read this syntax.

here is a version without lambda function and list comprehension

full_list = ['11-001-A001','03-003-B001', '05-002-C001', '02-023-B001', '06-013-A001','-']
#loop for get the header
lst_suff = []
for item in full_list:
	#get suffix
	suffix = item.split('-').pop(-1)
	#check if value 
	if suffix :
		#add to list
#remove duplicate
set_header = set(lst_suff)
#create group
out_list = []
for header in set_header:
	sublst = []
	for item in full_list:
		 if item.endswith(header):
	#insert the header
OUT = out_list
1 Like