+ 2
I can't understand this code. [Python]
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.
+ 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
+ 1
Lothar Thank you so much for your explanation.