Python's elegant way to sort numeric directories

I have a series of directories whose names are all called floating point values, for example:

0
1
2
2.5
6
6.1
10

      

I would like to get the latest (highest) numbered directory. Using the sort () method on directory names (which are strings) I get 10 immediately after 1.

dirs = os.listdir(path)
dirs.sort()

      

This gives the order:

0
1
10
2
2.5
6
6.1

      

I can put them on a float list by casting each to a float and then ordering the list, which solves the ordering problem. But then when I return the string value, I get 10.0, which is not a directory name. I need it to be exactly "10" (or whatever the last directory is called).

Is there an elegant way to do this?

+3


source to share


1 answer


You can use the sort keyword argument :

dirs = os.listdir(path)
dirs.sort(key=float)

      

The key argument must be a callable that will be called for each item in the list. Sorting is then performed with respect to the value returned by the callee, without changing the elements of the list themselves.



In this case, we use it float

as a callable that will return the floating point value represented by the strings passed to it.

Obviously this explodes with strings that are not floats ( ValueError

), but that seems to be outside the scope of your problem.

+6


source







All Articles