一个人如何根据指定的顺序或文件扩展名订购文件列表?我这样做的原因是因为我想循环浏览文件,然后按优先级顺序处理它们。在这种情况下是FBX。作为最后的选择,我将使用EXR。
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class XmlService {
items$: BehaviorSubject<Item[]> = new BehaviorSubject<Item[]>();
constructor() {
setTimeout(() => this.items.next([{age: '20'}]), 4000);
}
}
期望的目标
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']`
答案 0 :(得分: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']
答案 1 :(得分:0)
您可以创建一个字典,将扩展名映射到索引以用作排序的键:
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']