Home > Mobile >  How to sort a list of names based on substring?
How to sort a list of names based on substring?

Time:09-26

Say I have a file containing:

file1-01.json
file2-01.json
file3-01.json
file1-932.wav
file2-931.wav
file3-444.wav
file1-something.mp3
file2-something.mp3
file3-something.mp3

How can I turn it into:

file1-01.json
file1-932.wav
file1-something.mp3
file2-01.json
file2-931.wav
etc...

Code:

final_list = []

for i in line:
    basename = i.split(-)[0]
    group = [s for s in line if basename in s]
    final_list.append(group)

This approach seems a bit clunky when it comes to dealing with a huge file. any other efficient way of doing this?

CodePudding user response:

sorted_list = sorted(line, key=lambda x: x.split('-')[0])

CodePudding user response:

Since the substring you have is the first one, just using sorted will do the job:

print(sorted(my_list))

returns:

['file1-01.json',
 'file1-932.wav',
 'file1-something.mp3',
 'file2-01.json',
 'file2-931.wav',
 'file2-something.mp3',
 'file3-01.json',
 'file3-444.wav',
 'file3-something.mp3']
  • Related