Python中lambda、key与排序:sorted()与list.sort()相关疑问
Great questions—let’s break these down one by one to clear up the confusion!
1. Does sorted() have a return value?
Absolutely! Unlike list.sort(), which sorts the list in-place and returns None, sorted() creates and returns a brand new sorted list. The original iterable you pass to it stays completely unchanged.
For example:
original = [3, 1, 2] sorted_version = sorted(original) print(original) # Output: [3, 1, 2] (unchanged) print(sorted_version) # Output: [1, 2, 3] (new sorted list) # Compare with list.sort() original.sort() print(original) # Output: [1, 2, 3] (modified in-place) print(original.sort()) # Output: None (it returns nothing)
2. Why use sorted() instead of list.sort()?
There are three key scenarios where sorted() is the better choice:
- You need to keep the original data: If you still need the unsorted version of your iterable later,
sorted()is perfect because it doesn’t alter the original.list.sort()destroys the original order permanently. - You’re working with non-list iterables:
list.sort()is a method that only exists on lists. If you want to sort a tuple, string, generator, or any other iterable,sorted()handles them all and returns a sorted list as output. - Chaining operations: Since
sorted()returns a list, you can pass it directly to another function in one line. For example:# Works perfectly print(sorted([5, 2, 7])) # Output: [2,5,7] # Doesn't work as intended (prints None) print([5,2,7].sort()) # Output: None
3. What do x and y mean in sorting code?
This depends on where they’re used—there are two common cases:
Case 1: In key functions
When you use the key parameter (the most common approach in Python 3), x represents a single element from your iterable. The key function runs once per element, and returns a value that Python uses to determine the sort order.
For example:
people = [("Alice", 25), ("Bob", 20), ("Charlie", 30)] # x is each tuple (e.g., ("Alice",25)), we sort by the second element (age) sorted_people = sorted(people, key=lambda x: x[1]) print(sorted_people) # Output: [("Bob",20), ("Alice",25), ("Charlie",30)]
Case 2: In comparison functions (via functools.cmp_to_key)
If you’re using a custom comparison function (often wrapped with cmp_to_key in Python 3), x and y are two elements from your iterable that Python is comparing. The function returns:
- A negative number if
xshould come beforey - 0 if
xandyare equal in sort order - A positive number if
yshould come beforex
Example:
from functools import cmp_to_key numbers = [3, 1, 4, 2] # x and y are pairs of numbers; we return y-x to sort descending sorted_desc = sorted(numbers, key=cmp_to_key(lambda x, y: y - x)) print(sorted_desc) # Output: [4,3,2,1]
内容的提问来源于stack exchange,提问作者Pal Kol

