+ 2
I can't understand this code. [Python]
3 RĂ©ponses
+ 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.