首页 > 解决方案 > 谁能解释 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)

标签: python

解决方案


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)


推荐阅读