如何按文件扩展名的有序列表排序python文件列表[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

如何根据指定的订单或文件扩展名订购文件列表?我这样做的原因是因为我想循环遍历文件,然后按优先级顺序处理它们。在这种情况下是FBX。作为最后的手段,我会使用EXR。

files = [
    'Z:/users/john/apples.jpg',
    'Z:/users/john/apples.fbx',
    'Z:/users/john/apples.exr',
    'Z:/users/john/apples.abc',
]

ext = ['fbx','abc', 'jpg', 'exr']`

期望的目标

>>> files = [
    'Z:/users/john/apples.fbx',
    'Z:/users/john/apples.abc',
    'Z:/users/john/apples.jpg',
    'Z:/users/john/apples.exr',
]
python
2个回答
4
投票

使用查找index中的密钥list进行排序,

>>> import os
>>> files
['Z:/users/john/apples.jpg', 'Z:/users/john/apples.fbx', 'Z:/users/john/apples.exr', 'Z:/users/john/apples.abc']
>>> ext = ['fbx', 'abc', 'jpg', 'exr']
>>> sorted(files, key=lambda x: ext.index(os.path.splitext(x)[1].strip('.'))) # noqa
['Z:/users/john/apples.fbx', 'Z:/users/john/apples.abc', 'Z:/users/john/apples.jpg', 'Z:/users/john/apples.exr']

要处理,丢失钥匙,

>>> files.append('foo.bar')
>>> keys = {k: v for v, k in enumerate(ext)}
>>> sorted(files, key=lambda x: keys.get(os.path.splitext(x)[1].strip('.'), float('inf')))
['Z:/users/john/apples.fbx', 'Z:/users/john/apples.abc', 'Z:/users/john/apples.jpg', 'Z:/users/john/apples.exr', 'foo.bar']

0
投票

您可以创建一个将扩展映射到索引的dict,以用作排序的键:

indices = {k: i for i, k in enumerate(ext)}
sorted(files, key=lambda s: indices[s.rsplit('.', 1)[1]])

返回:

['Z:/users/john/apples.fbx', 'Z:/users/john/apples.abc', 'Z:/users/john/apples.jpg', 'Z:/users/john/apples.exr']
© www.soinside.com 2019 - 2024. All rights reserved.