+ 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

17th May 2018, 3:04 AM
Deepak Jayaprakash
Deepak Jayaprakash - avatar
4 odpowiedzi
+ 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.
18th May 2018, 9:05 PM
andrey
andrey - avatar
+ 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.
18th May 2018, 10:19 PM
Manuel Maier
Manuel Maier - avatar
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 ?
17th May 2018, 3:16 AM
Deepak Jayaprakash
Deepak Jayaprakash - avatar
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.
17th May 2018, 10:13 PM
Manuel Maier
Manuel Maier - avatar