+ 1
what does this lambda do in python sort. Assume a=[3,2,0,1] b=[1,0,3,2] b.sort(key = lambda x:a[x]) print(b) #res=2310
4 Answers
+ 1
manuel. you are in a right way . but its not depend on values in list "a". try for example with a=[5,7,4,6] ...or smth else. it works too.
+ 1
With a=[5,7,4,6] the result is [2,0,3,1]. I did not say that other a's will not work. Any a with at least four comparable elements will work for this b. So a=['d','f','c','e'] return the same. Other b's work only if any value could be used as index for a.
0
what I observed is if I replace an element of b to 9 ie., b=[1,0,9,3].I get an out of index error .Why is that ?
0
This code reorder the elenents of b so that when the lambda is applied to that list it is sorted.
When I apply the lambda to the result 2,3,1,0 I get
a[2],a[3],a[1],a[0] which is
0,1,2,3 and this is well sorted.
i b[i] a[b[i]]
0 1 2
1 0 3
2 3 1
3 2 0
Sort the lines using colum a[b[i]] and the colum b[i] is the result.
I hope this helps.