Python 中 key 参数的含义及用法
![](/theme/default/default/images/main/eye-open.png)
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
![](/theme/default/default/images/main/icon-jing.png)
Understanding the 'key' Parameter in Python Functions
In Python's sorted()
and other built-in functions such as map()
, min()
, and max()
, there is a key
parameter that allows users to define custom sorting rules. This summary explores the utility and significance of the key
parameter.
sorted()
and the key
Parameter
When using sorted()
, the key
parameter can be leveraged to sort lists based on various criteria. By default, sorted()
orders numbers in ascending order and strings alphabetically. To sort a list of names by length, the len
function can be passed as the key
:
reordered_names = sorted(some_names, key=len)
This instructs sorted()
to use the length of the names to determine their order.
Custom functions can also be specified as the key, as well as lambda functions for inline definitions. An example with a custom function is:
reordered_names = sorted(some_names, key=get_number_of_a_s)
Here, get_number_of_a_s
counts occurrences of the letter "a" to sort names.
A lambda function example would appear as:
reordered_names = sorted(some_names, key=lambda item: item.lower().count("a"))
list.sort()
and the key
Parameter
list.sort()
modifies the original list in place and, like sorted()
, accepts a key
parameter to define custom sorting criteria. However, it does not return a new list.
The key
Parameter in max()
and min()
Both max()
and min()
functions support the key
parameter to determine the maximum or minimum value based on a custom rule. For instance, to find the largest number in a list based on the sum of its digits:
max(numbers, key=lambda x: sum(int(y) for y in str(x)))
Other Uses of the key
Parameter
Functions like heapq.nlargest()
, heapq.nsmallest()
, and itertools.groupby()
also utilize the key
parameter. An example with itertools.groupby()
shows how to group a list of names by their length:
output = itertools.groupby(some_names, key=len)
This groups the names and returns an iterator with pairs of the group's key (the length of names) and the elements in that group.
想要了解更多内容?
![](/theme/default/default/images/main/icon-jing.png)
![](https://cdn.easycorp.cn/rongpm/upload/202312/f_39217d624bb2b42ce8f6322ebd7e573a.png)
![](https://cdn.easycorp.cn/rongpm/upload/202312/f_39217d624bb2b42ce8f6322ebd7e573a.png)