Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting with underscores

I'm trying to sort a list of files so that underscore chars are considered "later" than other ascii characters as seen in the example below (this is porting external software to python3). I'd like the sorting to account for file paths in the same way it was originally as to produce no diffs with the original sorting.

Requirements: Avoid 3rd party sorting modules if possible

files = sorted( files, key=lambda d: d['name'].lower() )

Example re-ordering which I'm trying to avoid

-/usr/wte/wte_scripts/wfaping.sh
 /usr/wte/wte_scripts/wfa_test_cli.sh
+/usr/wte/wte_scripts/wfaping.sh

I've searched for similar examples of sorting and couldn't find anything concrete with the same issue.

Thanks

like image 445
David Avatar asked Nov 01 '22 14:11

David


1 Answers

The easiest way would be to just replace "_" with a character that is "cosidered later" than letters (e.g. "{", the first ASCII character after "z") in the key function:

sorted(files, key=lambda d: d["name"].lower().replace("_", "{"))

If a sorting collision between "_" and "{" is not acceptable, the solution would be to write a custom comparator function which imposes the desired order, and write the sorting algorithm yourself as python3 no longer supports supplying your own cmp function to list.sort or sorted.

like image 148
l4mpi Avatar answered Nov 09 '22 11:11

l4mpi