-2

I am new to python and I have a question


A = [3,2,4,1]
N = len(A)
B = sorted(range(N), key = lambda i: A[i])
print(B)
output #[3, 1, 0, 2]

input #A = [7,2,4,1]
output #[3, 1, 2, 0]

I do not understand the output ?? Can anyone explain to me?

Senthil
  • 71
  • 4
  • This is kind of numpy argsort. It's giving you the index of the sorted array. For the first array, the sorted list is [1, 2, 3, 4], so the arg list is [3, 1, 0, 2] – Osman Mamun Nov 18 '19 at 19:21
  • Possible duplicate of [Syntax behind sorted(key=lambda: ...)](https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda) and [What is key=lambda](https://stackoverflow.com/questions/13669252/what-is-key-lambda) and [What does this mean: key=lambda?](https://stackoverflow.com/questions/16310015/what-does-this-mean-key-lambda-x-x1) – pault Nov 18 '19 at 19:22
  • https://docs.python.org/3.5/howto/sorting.html#sortinghowto – Grzegorz Skibinski Nov 18 '19 at 19:23

2 Answers2

1

Let's talk about the specific example you have used

A = [3, 2, 4, 1]

N = len(A) . # N = 4

B = sorted(range(N), key = lambda i: A[i]) # sorted([0,1,2,3], key= lambda i:A[i])

Basically you are trying to sort [0,1,2,3] based on the values A[i] which are [3,2,4,1]

Now, A[3] < A[1] < A[0] < A[2]

And so you get the answer as [3, 1, 0, 2]

Vishal
  • 3,178
  • 2
  • 34
  • 47
0

In the sorted function the first element is the item you would like to sort. If you can you sort a generator that is converted to a list of size 4. The sorting function sorts according to the value given by the anonymous function.

In your case - A = [3, 2, 4, 1] List to sort - [0, 1, 2, 3]. Keys for each element [3, 2, 4, 1]. Basically you can imagine you sort [(0, 3), (1, 2), (2, 4), (3, 1)] according to the second element and then left with the first element and this results [3, 1, 0, 2] you get.

Tom Ron
  • 5,906
  • 3
  • 22
  • 38