Last active
October 23, 2020 04:05
-
-
Save lhz/379f03e5da135af982cb69fa2b732fc9 to your computer and use it in GitHub Desktop.
Sort list of strings containing Null values with Nulls at the end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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