Created
May 15, 2016 07:27
-
-
Save giwa/b1ef8d0a3d9b0353eed37ffcf4571e91 to your computer and use it in GitHub Desktop.
Custom sort in Python3 ref: http://qiita.com/giwa/items/afd1476c5211e28361ba
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
>>> def compare(a, b): | |
... """Comparison that ignores the first letter""" | |
... return cmp(a[1:], b[1:]) | |
>>> names = ['Adam', 'Donald', 'John'] | |
>>> names.sort(cmp=compare) | |
>>> names | |
['Adam', 'John', 'Donald'] | |
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
>>> names = ['Adam', 'Donald', 'John'] | |
>>> names.sort(key=lambda x: x[1:]) | |
>>> names | |
['Adam', 'John', 'Donald'] | |
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
>>> l = [('betty', 1), ('a', 1), ('butter', 2)] | |
>>> def custom_key(x): | |
... return -x[1], x[0] | |
... | |
>>> l.sort(key=custom_key) | |
>>> l | |
[('butter', 2), ('a', 1), ('betty', 1)] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment