python - 如何按字典顺序对文件路径进行排序? Python

标签 python file sorting path lexicographic

我需要将文件路径列表按字典顺序排序,例如输出按如下方式排序:

C:\Test\Project1\Example\test1.txt   
C:\Test\Project1\Example\test2.txt   
C:\Test\Project1\Example\Sub\meee.txt       
C:\Test\Project1\Example\Sub\test1.txt    
C:\Test\Project1\Example\Sub\youu.txt   
C:\Test\Project1\Example\Zzz\zzz.py

当我自然排序时,我在 C:\Test\Project1\Example\test1.txt 之前收到 C:\Test\Project1\Example\Sub\meee.txt > 并且不希望这样。

最佳答案

您可以将sorted与自定义键一起使用,该键优先考虑根目录中的文件:

L = [r'C:\Test\Project1\Example\test1.txt', r'C:\Test\Project1\Example\test2.txt',
     r'C:\Test\Project1\Example\Sub\meee.txt', r'C:\Test\Project1\Example\Sub\test1.txt',   
     r'C:\Test\Project1\Example\Sub\youu.txt', r'C:\Test\Project1\Example\Zzz\zzz.py']

def sort_key(x):
    splits = x.split('\\')[4:]
    return len(splits), splits

res = sorted(L, key=sort_key)

['C:\\Test\\Project1\\Example\\test1.txt',
 'C:\\Test\\Project1\\Example\\test2.txt',
 'C:\\Test\\Project1\\Example\\Sub\\meee.txt',
 'C:\\Test\\Project1\\Example\\Sub\\test1.txt',
 'C:\\Test\\Project1\\Example\\Sub\\youu.txt',
 'C:\\Test\\Project1\\Example\\Zzz\\zzz.py']

关于python - 如何按字典顺序对文件路径进行排序? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693903/

相关文章:

python - 如何在不安装解释器的情况下部署 Perl/Python/Ruby 脚本?

c - 将文件内容传递到内存时出现错误

python - 理解如何在 Python 的合并排序中存储和传递值的概念的问题

c - 如何在C中将图像排序成行

python - TensorFlow 服务 : Update model_config (add additional models) at runtime

python - 使用 python 对 wav RIFF 文件进行下采样

python - SQLAlchemy 连接错误

python - 如何将python float转换为要在C++程序中解释的字节

Java:如何从文件中获取缩略图

java - 创建随机数组以便对排序算法进行计时