简体   繁体   中英

Python sorted function

Can someone explain why below lambda sorted return this result?

Example 1

>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
[5, 4, 6, 3, 7, 2, 8, 1, 9]

Example 2

sorted ([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(2-x))
[2, 1, 3, 4, 5, 6, 7, 8, 9]

I understand how normal student.age acs sorting work but not the example at top

>>student_objects = [
        Student('john', 'A', 15),
        Student('jane', 'B', 12),
        Student('dave', 'B', 10),
]
>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

key says "instead of sorting by the actual value at each position, compute a new value, sort by that, and then place the original values where the new ones would sort in the list".

So starting with the original list:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

The key lambda is called for each item, creating the following key values (in parens):

[1 (4),
 2 (3),
 3 (2),
 4 (1),
 5 (0),
 6 (1),
 7 (2),
 8 (3),
 9 (4)]

The list is then sorted in the order of the key values:

[5 (0),
 4 (1),
 6 (1),
 7 (2),
 3 (2),
 2 (3),
 8 (3),
 1 (4),
 9 (4)]

And then the original values from the list list are returned in that order:

[5, 4, 6, 3, 7, 2, 8, 1, 9]

The key function returns the value by which sorting takes place. If you want to understand abs(5 - x) influences the sort, calculate the values for the given list:

>>> values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> key = lambda x: abs(5 - x)
>>> [(v, key(v)) for v in values]
[(1, 4), (2, 3), (3, 2), (4, 1), (5, 0), (6, 1), (7, 2), (8, 3), (9, 4)]

So sorted() will put the list in the order that the key values would be sorted into. For 5 , the key returns 0 , and that's the lowest value and would come first. For 1 and 9 , the key returns 4 , and those then are sorted last. Anywhere the key produces equal values (like 3 for both the input values 2 and 8 ), the inputs are kept in their original order:

>>> sorted([(v, key(v)) for v in values], key=lambda vk: vk[1])  # sort on the key output
[(5, 0), (4, 1), (6, 1), (3, 2), (7, 2), (2, 3), (8, 3), (1, 4), (9, 4)]
>>> #^       ^       ^       ^       ^       ^       ^       ^       ^

What sorted() then returns, are the original input values alone, without the outputs of the sort key.

In the end, the key caused the values to be sorted by distance from 5 . The values closest to 5 come first, the values furthest away come last.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM