Skip to content

Instantly share code, notes, and snippets.

@leetschau
Created May 28, 2016 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leetschau/93dad4e94b8234a7966fd0092266639d to your computer and use it in GitHub Desktop.
Save leetschau/93dad4e94b8234a7966fd0092266639d to your computer and use it in GitHub Desktop.
Python sorted 函数,当某项不包含排序依据时,可以将fallback值作为自己的排序依据
aa = [{'a': 3}, {'a': 2}, {'a': 5}, {'b':8}]
sorted(aa, key=lambda rec: rec['a'] if 'a' in rec else 1, reverse=True)
#: [{'a': 5}, {'a': 3}, {'a': 2}, {'b': 8}]
sorted(aa, key=lambda rec: rec['a'] if 'a' in rec else 6, reverse=True)
#: [{'b': 8}, {'a': 5}, {'a': 3}, {'a': 2}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment