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