26th Mar 2019, 4:15 PM
Abdul S Ansari
Abdul S Ansari - avatar
3 Answers
+ 10
hi Samad, I will try to explain it: def custom_sort(t): return t[1] L = [("Alice", 25), ("Bob", 20), ("Alex", 5)] L.sort(key=custom_sort) print(L) Ouput of this code is: [('Alex', 5), ('Bob', 20), ('Alice', 25)] 1. A list ā€˜Lā€™ is created with 3 pair of ā€˜nameā€™ and ā€˜ageā€™ information. 2. Next the ā€˜sortā€™ method is called, giving it one argument ā€˜keyā€™ which means to which information the sort should work. 3. ā€˜key=custom_sortā€™ means that instead of giving the key argument directly to sort, a user function ā€˜custom_sortā€™ is called. User function id defined at the top of the code. 4. Function ā€˜custom_sortā€™ returns ā€˜[1]ā€™ which is an index for the sort method. For sorting to ā€˜nameā€™ the index has to be [0] as name is the first information. So sorting to [1] means its sorted to ā€˜ageā€™ as the second information. Output with index [0] for ā€˜nameā€™ is: [('Alex', 5), ('Alice', 25), ('Bob', 20)] Hope this helps.
26th Mar 2019, 4:37 PM
Lothar
Lothar - avatar
+ 3
Samad, I have attached to you a sample file py which I did a few says before to a very similar request like yours. https://code.sololearn.com/c5u83K00g9yO/?ref=app
26th Mar 2019, 6:06 PM
Lothar
Lothar - avatar
+ 1
Lothar Thank you so much for your explanation.
27th Mar 2019, 8:30 AM
Abdul S Ansari
Abdul S Ansari - avatar