Joey Joestar
Joey Joestar

Reputation: 235

How to sort a list of names based on substring?

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?

Upvotes: 0

Views: 533

Answers (2)

Amin
Amin

Reputation: 2874

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

Upvotes: 1

Mohammad
Mohammad

Reputation: 3396

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']

Upvotes: 0

Related Questions