Skip to content

Instantly share code, notes, and snippets.

@lhz
Last active October 23, 2020 04:05
Show Gist options
  • Save lhz/379f03e5da135af982cb69fa2b732fc9 to your computer and use it in GitHub Desktop.
Save lhz/379f03e5da135af982cb69fa2b732fc9 to your computer and use it in GitHub Desktop.
Sort list of strings containing Null values with Nulls at the end
#!/usr/bin/env python3
from locale import strcoll
from functools import cmp_to_key
def null_last_cmp(a, b):
"""Comparison function that rates non-Null values lower than Null"""
if a is None:
return 0 if b is None else 1
return -1 if b is None else strcoll(a, b)
values = ["abc", None, "def"]
print(sorted(values, key=cmp_to_key(null_last_cmp)))
# => ['abc', 'def', None]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment