sorted(range(-3,4), key=lambda x: x*x)
Try to do it step by step.
Let's start with range
, range
here will provide numbers -3
, -2
, -1
, 0
, 1
, 2
, and 3
.
sorted
then runs on each of these items and uses the function provided in the key
parameter. Each of these items is passed on the x
parameter of the lambda
. The lambda
then handles this x
(represented as the number in the range
) and performs some operations, in your case, it just gets the square of the number x
. The square value then gets returned and the sorted
function uses this returned square value in comparing in ascending order (remember that sorted
arranges the list in ascending order unless specified as reverse=True
).
The purpose of the key
function is to only tell how to compare each item in the iterable/list passed. But it does not affect the final list of elements that will be returned. It will still use the passed list. So these values -3
, -2
, -1
, 0
, 1
, 2
, and 3
will be the elements of the returned list by the sorted
function, only arranged in accordance with the key
parameter.
Hope it helps and makes sense.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…