Last active
April 29, 2020 10:41
-
-
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
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
""" | |
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