Skip to content

Instantly share code, notes, and snippets.

@Anexen
Created July 24, 2024 07:08
Show Gist options
  • Select an option

  • Save Anexen/797f4aa7de5d78bab9b1fc9f0e1a3a10 to your computer and use it in GitHub Desktop.

Select an option

Save Anexen/797f4aa7de5d78bab9b1fc9f0e1a3a10 to your computer and use it in GitHub Desktop.
SQL-like sorting for python
class Desc:
__slots__ = ("value",)
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value > other.value
data = [
{"x": 2, "y": "a"},
{"x": 2, "y": "b"},
{"x": 1, "y": "b"},
]
sorted(data, key=lambda x: (x["x"], Desc(x["y"])))
sorted(data, key=lambda x: (Desc(x["x"]), x["y"]))
sorted(data, key=lambda x: (Desc(x["x"]), Desc(x["y"])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment