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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With