Skip to content

Instantly share code, notes, and snippets.

@jonathanagustin
Last active April 29, 2020 10:41
Show Gist options
  • Save jonathanagustin/dd1899ec74543daa57f6e00d9f36ec85 to your computer and use it in GitHub Desktop.
Save jonathanagustin/dd1899ec74543daa57f6e00d9f36ec85 to your computer and use it in GitHub Desktop.
Example python sort with lambda function that determines what to do if there is a tie
"""
https://py.checkio.org/forum/post/9298/sorted-function-explanation-please/
This will sort a list of tuples by strings (second tuple item)
and then by number in reversed order when strings are equal.
"""
list_of_tuples = [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
list_of_tuples.sort(key=lambda t:(t[1], -t[0]))
print(list_of_tuples)
# [(2, 'a'), (1, 'a'), (2, 'b'), (1, 'b')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment