+ 6
Sort list using key and lambda
Could someone explain the output of the following please: a = [3, 2, 0, 1] b = [1, 0, 3, 2] b.sort(key = lambda x: a[x]) print(b) Why the result is [2, 3, 1, 0] ? Thanks
6 odpowiedzi
+ 5
Sorting using '
b.sort(key = lambda x: a[x])' means using values of a[b[i]] instead of b[i] to compare the elements. So the result is [2, 3, 1, 0] because:
a[b[2]] <= a[b[3]] <= a[b[1]] <= a[b[0]]
as
0 <= 1 <= 2 <= 3
+ 22
Hey Ingrid Horatius, I ll try to explain what's going on.
# 1. iteration a[x] = 3 so b[3] = 2
# 2. iteration a[x] = 2 so b[2] = 3
# 3. iteration a[x] = 0 so b[0] = 1
# 4. iteration a[x] = 1 so b[1] = 0
+ 6
My understanding is, what the key parameter does is it assigns a value to each element of the sortable list b. This value is then used to establish the order.
In the lambda function we use a custom function to establish these "rank" values, using the elements of the list a.
So the result of lambda x: a[x]
b[0]=1 gets the rank a[1]=2
b[1]=0 gets the rank a[0]=3
b[2]=3 gets the rank a[3]=1
b[3]=2 gets the rank a[2]=0
So the value 2 has the lowest rank (0) etc, hence the final order [2,3,1,0]
Check also this article that has an excellent explanations, also on what happens if the rank values are equal.
https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda
+ 2
Thank you for your answer I got it now :)
+ 1
Janusz Bujak 🇵🇱 What do you mean?
+ 1
Janusz Bujak 🇵🇱 a[b[i]]
because key is lambda x: a[x]
IF f(x) = a[x]
THEN f(b[i]) = a[b[i]]
i.e. b is softed by the values returned by the lambda function