Skip to content

Instantly share code, notes, and snippets.

@plavjanik
Created June 16, 2022 08:54
Show Gist options
  • Save plavjanik/9f5d2769daa7e9efacdea38aedea1400 to your computer and use it in GitHub Desktop.
Save plavjanik/9f5d2769daa7e9efacdea38aedea1400 to your computer and use it in GitHub Desktop.
Custom sort order
colors = ["cyan", "magenta", "yellow", "black"]
def compare_length(c1, c2):
if len(c1) < len(c2):
return -1
if len(c1) > len(c2):
return 1
return 0
# Python 2 ❌
print(sorted(colors, cmp=compare_length))
# Python 3 ❌
from functools import cmp_to_key
print(sorted(colors, key=cmp_to_key(compare_length)))
# ✔️
print(sorted(colors, key=len))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment