是否有一个内置函数可以一步对python列表进行排序和过滤?

Ben*_*Ben 8 python

给定一个带有数字名称的文件目录,我目前分两步对目录列表进行排序和过滤.

#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]

firstFile =  5
lastFile  = 15

#filter out any files that are not in the desired range
files = filter(lambda f: int(f) >= firstFile and int(f) < lastFile, files)

#sort the remaining files by timestamp
files.sort(lambda a,b: cmp(int(a), int(b)))
Run Code Online (Sandbox Code Playgroud)

是否有一个python函数结合了筛选和排序操作,所以列表只需要迭代一次?

ken*_*ytm 22

那些是正交的任务,我不认为它们应该是混合的.此外,使用生成器表达式可以轻松地在一行中进行过滤和排序

files = sorted( (f for f in files if firstFile <= int(f) < lastFile), key=int)
Run Code Online (Sandbox Code Playgroud)

  • 不,它不会创建元组,而是创建一个生成器。没有临时元组。 (2认同)