python - 谁能解释 lambda 函数如何作为排序方法中的键工作?
问题描述
我知道这里的 sorted 方法按升序对我的列表进行排序,但是这个 lambda 函数如何改变我的代码的功能?
list = [ (1,4), (0,8), (5,6), (7,10)]
list_sorted = sorted(list, key = lambda list: list[1], reverse = False)
print("Sorted:", list_sorted)
解决方案
The key
parameter of the sorted
function modifies the sorting. Instead of comparing based on the values, it'll compare based off the value returned by the key
function. In this case, key
returns the second element of the tuple, so the list will be sorted based off the second element of the tuple, and not the first like tuples normally are.
See the official docs for more info.
(to be pedantic tuples aren't sorted by the first element, they're sorted lexicographically starting from the first element)
推荐阅读
- php - PHP 7.4:如何检查类型属性是否已初始化(包括使用 null 进行初始化)?
- mysql - SQL分组更多表
- node.js - 如何在 react.js 中获取这些注释数组的值?
- c++ - libssh 文件操作下载和上传速度慢
- javascript - 在不重新渲染子组件的情况下反应父组件的 setState
- python - 计算组内独特组合的权重
- javascript - 不必要的条件渲染不会在脚本标签版本 React 中完全重新渲染相同级别的元素
- autodesk-forge - onComplete 回调可以与 localhost 一起使用吗?
- git - 当我从特定提交(合并提交)创建分支时,一些较早的提交被删除
- jquery - 单击按钮并自动选择包含相同文本的选项