Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Given a directory of files all with numeric names, I currently sort and filter the directory list 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 the filter and sort operations so the list only needs to be iterated over once?

like image 890
Ben Avatar asked Dec 20 '10 17:12

Ben


People also ask

How do you sort a list inbuilt function in Python?

sort() in Python The sort function can be used to sort the list in both ascending and descending order. To sort the list in ascending order. Its time complexity is O(NlogN). This function can be used to sort list of integers, floating point number, string and others.

Does Python have a sort function?

Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.

What is filter () function in Python?

Python's filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition. This process is commonly known as a filtering operation.


2 Answers

Those are orthogonal tasks, I don't think they should be mixed. Besides, it's easy to filter and sort separately in one line with generator expressions

files = sorted( (f for f in files if firstFile <= int(f) < lastFile), key=int)
like image 95
kennytm Avatar answered Oct 05 '22 18:10

kennytm


The most straightforward way to do this is (in 2.6 at least) 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]

The underlying sequence doesn't get traversed and filtered until sorted starts iterating over it.

like image 24
Robert Rossney Avatar answered Oct 05 '22 17:10

Robert Rossney