Py学习  »  Python

python sort()函数不按预期排序[重复]

jane • 5 年前 • 1533 次点击  

这个问题已经有了答案:

我对python很陌生,不知道如何让.sort()函数工作。

我的计算机上有一个.txt文件文件夹,我正试图按文件名排序。它们的标题是poem_1.txt到poem_600.txt。到目前为止,这就是我所拥有的:

   import os
    all_poems=[]
    for root, dirs, files in os.walk(mydir):
        for file in files:
            if file.endswith(".txt"):
                all_poems.append(os.path.join(root, file))
    n_files = len(all_poems)

然后我可以通过使用

all_poems[600]

那么,我知道

 all_poems.sort()

它给了我诗歌的顺序:

'poem_1.txt', 'poem_10.txt', 'poem_100.txt', 'poem_11.txt', 'poem_12.txt', 'poem_13.txt', 'poem_14.txt', 'poem_15.txt', 'poem_16.txt', 'poem_17.txt', 'poem_18.txt', 'poem_19.txt', 'poem_2.txt', 'poem_20.txt', 'poem_21.txt'

我做错什么了?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47345
 
1533 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Rocky Li
Reply   •   1 楼
Rocky Li    6 年前

使用 sort 具有 key 要修复:

all_poems = sorted(all_poems, key=lambda x: int(x.split('_')[1].split('.')[0]))

或:

# sort on self.
all_poems.sort(key=lambda x: int(x.split('_')[1].split('.')[0]))

这将根据文件编号和结果进行排序:

>>> all_poems:

['poem_1.txt',
 'poem_2.txt',
 'poem_10.txt',
 'poem_11.txt',
 'poem_12.txt',
 'poem_13.txt',
 'poem_14.txt',
 'poem_15.txt',
 'poem_16.txt',
 'poem_17.txt',
 'poem_18.txt',
 'poem_19.txt',
 'poem_20.txt',
 'poem_21.txt',
 'poem_100.txt']