You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sorted方法中lambda函数作为key的作用及代码功能变化解析

How Lambda Functions Work as the key Parameter in sorted()

Let me break this down for you clearly—this is one of the most practical uses of lambda functions, so let’s start with the basics and work through your example step by step.

First, the Default Behavior of sorted()

By default, sorted() sorts iterables based on the natural order of their elements. For tuples (like the ones in your list), it compares the first element of each tuple first. If those are equal, it moves to the second element, and so on.

For your original list:

list = [ (1,4), (0,8), (5,6), (7,10)]

The default sorted result would be [(0,8), (1,4), (5,6), (7,10)]—since it’s sorting by the first element of each tuple (0 < 1 < 5 < 7).

What the key Parameter Does

The key parameter lets you override the default sorting logic. It takes a function that runs on every element in your list. Instead of sorting the elements themselves, sorted() will sort the elements based on the value returned by this function for each element.

Your Lambda Function Explained

In your code:

list_sorted = sorted(list, key = lambda list: list[1], reverse = False)

Let’s unpack that lambda:

  • lambda list: list[1] is a tiny anonymous function. Here, list is just the parameter name (pro tip: use something like item instead to avoid confusion with the built-in list type, but it works either way).
  • For each tuple in your original list, this lambda function takes the tuple and returns its second element (Python uses 0-indexing, so [1] refers to the second item in the tuple).

So instead of sorting by the first element of each tuple, sorted() now sorts by the second element.

Let’s Walk Through the Example

Original list tuples and their second elements:

  • (1,4) → 4
  • (0,8) → 8
  • (5,6) → 6
  • (7,10) → 10

When sorted in ascending order (reverse=False, which is the default), the order of these second elements is 4 → 6 → 8 → 10. So the sorted list will be the tuples paired with these values, in that order:

[(1,4), (5,6), (0,8), (7,10)]

A Quick Note on reverse=False

This just tells sorted() to use ascending order (smallest to largest). If you set reverse=True, it would sort in descending order, giving you [(7,10), (0,8), (5,6), (1,4)].

内容的提问来源于stack exchange,提问作者user12211053

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:17:51