Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

list - Python sorting with square as key

Saw some code on a book and just cannot follow it, even try to decipher by run step-by-step and it's still Greek to me... (on 2nd Mon. journey) (I kind of know each part, eg. range or sorted or lambda- except putting together)

sorted(range(-3,4), key=lambda x: x*x)

Output:

[0,-1,1,-2,2,-3,3]
question from:https://stackoverflow.com/questions/65838189/python-sorting-with-square-as-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...