Created
August 29, 2016 06:33
-
-
Save suriyadeepan/3f90ca38ed701baeead09b39e1c0475a to your computer and use it in GitHub Desktop.
Sort a list based on more than one attribute
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
lst = [ 'file', 'if', 'hat', 'zoltan', 'calculator', 'cup', 'pocket', 'symbolic', 'I', 'attributes' ] | |
sorted_lst1 = sorted(lst, key=len) | |
print(sorted_lst1) | |
## OUTPUT : ['I', 'if', 'hat', 'cup', 'file', 'zoltan', 'pocket', 'symbolic', 'calculator', 'attributes'] | |
sorted_lst2 = sorted(lst, key=lambda item : (len(item),item[0]) ) | |
print(sorted_lst2) | |
## OUTPUT : ['I', 'if', 'cup', 'hat', 'file', 'pocket', 'zoltan', 'symbolic', 'attributes', 'calculator'] | |
# alternative to lambda | |
def len_alpha(item): | |
return ( len(item), item[0] ) | |
sorted_lst3 = sorted(lst, key = len_alpha) | |
# compare sorted_lst2 and sorted_lst3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment