你只需要通过强制转换为int数字排序,使用最后一个字母打破平局:
lst = ['categoryc.2.file','categorya.1.file','categorya.2.file',
'categoryb.2.file','categoryb.1.file','categoryc.1.file']
def key(x):
spl = x.split(".",2)
return int(spl[1]),spl[0][-1]
lst.sort(key=key)
输出:
['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file',
'categorya.2.file', 'categoryb.2.file', 'categoryc.2.file']
如果你不关心顺序一旦类别进行分组,然后只使用int
:
lst = ['categoryc.2.file','categorya.1.file','categorya.2.file',
'categoryb.2.file','categoryb.1.file','categoryc.1.file']
lst.sort(key=lambda x: int(x.split(".",2)[1]))
print(lst)
['categorya.1.file', 'categoryb.1.file', 'categoryc.1.file',
'categoryc.2.file', 'categorya.2.file', 'categoryb.2.file']
.sort
被就地所以你不需要建立任何其他列表。
_best_方式取决于你在做什么,这个列表来自哪里以及真实数据是什么样子。 – Cyphase
为了简单起见,我删除了上下文。但我所拥有的是我想以特定顺序阅读的文件名列表。为了实现这一点,我想按照主文章中所述的方式对列表重新排序。 – Samuel