Is there a built-in function to sort and filter a python list in one step?

Given the directory of all files with numerical names, I am currently sorting and filtering the list of directories in two steps.

#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))) 

Is there a python function that combines filtering and sorting operations so that the list needs to be repeated only once?

+4
source share
2 answers

These are orthogonal tasks, I don’t think they need to be mixed. In addition, it is easy to filter and sort separately on the same line as generator expressions.

 files = sorted( (f for f in files if firstFile <= int(f) < lastFile), key=int) 
+18
source

The easiest way to do this (at least in 2.6) is to create a filtering generator using itertools.ifilter , and then sort it:

 >>> from itertools import ifilter >>> seq = [ 1, 43, 2, 10, 11, 91, 201] >>> gen = ifilter(lambda x: x % 2 == 1, seq) >>> sorted(gen) [1, 11, 43, 91, 201] 

A suitable sequence does not pass and is not filtered until sorted starts repeating it.

0
source

Source: https://habr.com/ru/post/1332797/


All Articles