+ 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

2nd Jan 2019, 7:43 PM
Ingrid Horatius
Ingrid Horatius - avatar
6 Antworten
+ 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
2nd Jan 2019, 9:20 PM
portpass
+ 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
2nd Jan 2019, 9:10 PM
r8w9
r8w9 - avatar
+ 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
2nd Jan 2019, 9:33 PM
Tibor Santa
Tibor Santa - avatar
+ 2
Thank you for your answer I got it now :)
2nd Jan 2019, 9:33 PM
Ingrid Horatius
Ingrid Horatius - avatar
+ 1
Janusz Bujak 🇵🇱 What do you mean?
14th Mar 2019, 9:30 AM
portpass
+ 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
14th Mar 2019, 11:07 AM
portpass