python sort strings with leading numbers alphabetically

旧街凉风 提交于 2019-12-25 18:26:45

问题


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
2_file
21_file
22_file ...

If they were just numbers as strings ('1') without the underscore I could sort them with sorted(). I have tried different sort-methods with different key-attributes, also the module "natsort", but with no result. Do I have to write my own algorithm for this? Maybe I could extract the leading numbers and use them for sorting?

UPDATED desired list to correct listing


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



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



回答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



回答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


来源:https://stackoverflow.com/questions/48469254/python-sort-strings-with-leading-numbers-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!