I have a csv file with raws of different sizes that contain values and a header for each raw.
00_A1_s1
00_A1_s2
00_A1_s3
04_A1_s1
04_A1_s2
04_A1_s3
08_A1_s1
08_A1_s2
08_A1_s3
and I want to group the raws by the name and then order them by the number in front of the coordinates
00_A1_s1
04_A1_s1
08_A1_s1
00_A1_s2
04_A1_s2
08_A1_s2
00_A1_s3
04_A1_s3
08_A1_s3
Thanks!
CodePudding user response:
You could use sort
built-in function with the key
parameter which accepts a function where you can infer the order condition on the elements. It returns a new list.
# file names
l = """00_A1_s1
00_A1_s2
00_A1_s3
04_A1_s1
04_A1_s2
04_A1_s3
08_A1_s1
08_A1_s2
08_A1_s3"""
l = l.split('\n') # file names as list
# sort wrt the last group of characters
print(sorted(l, key=lambda p: p.split('_')[-1]))
Output
04_A1_s1
08_A1_s1
00_A1_s2
04_A1_s2
08_A1_s2
00_A1_s3
04_A1_s3
08_A1_s3
CodePudding user response:
You can use sorted
and use tuple
for each item that is most important in sorting order like below:
txt = """00_A1_s1
00_A1_s2
00_A1_s3
04_A1_s1
04_A1_s2
04_A1_s3
08_A1_s1
08_A1_s2
08_A1_s3"""
lst = txt.split('\n')
def orderSort(item):
splt_itm = item.split('_')
# first sorting on `A*` then on `s*` and at end consider number
return (splt_itm[1] , splt_itm[2] , splt_itm[0])
result = sorted(lst, key=lambda x : orderSort(x))
print('\n'.join(result))
Output:
00_A1_s1
04_A1_s1
08_A1_s1
00_A1_s2
04_A1_s2
08_A1_s2
00_A1_s3
04_A1_s3
08_A1_s3