Python Sort Strings With Leading Numbers Alphabetically
I have a list of filenames, each of them beginning with a leading number: 10_file 11_file 1_file 20_file 21_file 2_file ... I need to put it in this order: 1_file 10_file 11_file
Solution 1:
Sorting, splitting and list comprehensions work well here.
lst = ['10_file', '11_file', '1_file', '20_file', '21_file', '2_file']
lst_split = ['_'.join(x) for x in sorted(i.split('_') for i in lst)]
# ['1_file', '10_file', '11_file', '2_file', '20_file', '21_file']
Solution 2:
Edited with what the OP really wanted:
>>> from functools import partial
>>> lst = ['10_file', '11_file', '1_file', '20_file', '21_file', '2_file']
>>> sorted(lst, key=partial(str.split, sep='_', maxsplit=1))
['1_file', '10_file', '11_file', '2_file', '20_file', '21_file']
Solution 3:
How about this:
flist = ['10_file',
'11_file',
'1_file',
'20_file',
'21_file',
'2_file']
tempdict = {}
for item in flist:
num = item.split('_')[0]
tempdict[num] = item
output = []
# for truly numeric sorting#for k in sorted([int(k) for k in tempdict.keys()]):#output.append(tempdict[str(k)])# for alphabetical sorting:for k in sorted(tempdict.keys()):
output.append(tempdict[k])
print('\n'.join(output))
Result
1_file
10_file
11_file
2_file
20_file
21_file
Solution 4:
The simple way. Just extract the digits and then sort it as string:
sorted(l, key=lambda s: s.split("_")[0] )
That's all you need... try:
l=['2_file', '10_file', '11_file', '1_file', '20_file', '21_file']
print"\n".join(sorted(l, key=lambda s: s.split("_")[0] ))
1_file
10_file
11_file
2_file
20_file
21_file
Post a Comment for "Python Sort Strings With Leading Numbers Alphabetically"