+ 1
Sort with key
This is a question from a python challenge. Can anyone please help me understand the result. a=[3,2,0,1] b=[1,0,3,2] b.sort(key=lambda x:a[x]) print(b) The output is [2, 3, 1, 0] Why? What if list a contain numbers that are beyond 0-3.
5 Answers
+ 4
Now what this code is doing is
a = [3,2,0,1]
b = [1,0,3,2]
b.sort(key = lambda x: a[x])
It arranges list b according to the values of keys given.
Here we take x from b
The keys will be
element of b --> a[element of b] == key value
1 --> a[1] == 2
0 --> a[0] == 3
3 --> a[3] == 1
2 --> a[2] == 0
On arranging this we get
2 -->0
3 -->1
1--> 2
0 -->3
which is the output!
But if you put something like 4 or 5 in b, it will give an error because
5 --> a[5] which does not exist and hence list index out of bound.
I hope you understand!
+ 1
Yes! But if you change the list b and add more than 3 then it will show error...
I will explain it in a moment... wait
0
You can try it in code playground to find out...
0
I did try and couldn't make sense of it. The result changes according to numbers in a.
0
Peng Yu
Your code asks to rearrange list b.
To do this you have to tell Python the new order, which is conveyed using b.sort(key = the new order)
The new order here is the contents of list a.
a[0] = 3, so it means b[0] = b[3] = 2 to Python,
a[1] = 2, which means b[1] = b[2] = 3,
a[2] = 0, which means b[2] = b[0] =1,
a[3] = 1, which means b[3] = b[1] = 0.
So b is now [2,3,1,0]