I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.

For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.

For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.

  1. Using lamba ultimately means you don't have to write (define) an entire function, like the one sblom provided an example of. Lambda functions are created, used, and immediately destroyed - so they don't funk up your code with more code that will only ever be used once. This, as I understand it, is the core utility of the lambda function and its applications for such roles are broad. Its syntax is purely by convention, which is in essence the nature of programmatic syntax in general. Learn the syntax and be done with it.

lambda input_variable/s: instruction

e.g.

lambda x: x/2

...which means for each x in some iterable, return x divided by 2.

  1. The idea behind the key argument is that it takes in a set of instructions that essentially point 'sorted()' at which list elements it should use to sort by. When it says 'key=', what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list.

Check it out:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)

Base example:

sorted(mylist)

[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.

Example 1:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)

[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?

Notice that my lambda function told sorted to check if (e) was even or odd before sorting.

BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0) and second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on

each list element prior to making comparisons.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

What does the example using a modulo return? A boolean value: True=1, False=0. So how does sorted deal with this key? It bascially transforms the original list to a sequence of 1s and 0s.

[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0,0,0,1,1,1,1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list,tuple,dict, etc. again determined by the lambda function.

Lets try and predict what happens when I run the following code.

mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])

My sorted methods obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:

[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]

Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.

This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.

Syntax behind sorted(key=lambda :)的更多相关文章

  1. python3排序 sorted(key=lambda)--实现对字典按value值排序

    使用python对列表(list)进行排序,说简单也简单,说复杂也复杂,我一开始学的时候也搞不懂在说什么,只能搜索一些英文文章看看讲解,现在积累了一些经验,写在这里跟大家分享, 1.sorted函数首 ...

  2. python3排序 sorted(key=lambda)

    使用python对列表(list)进行排序,说简单也简单,说复杂也复杂,我一开始学的时候也搞不懂在说什么,只能搜索一些英文文章看看讲解,现在积累了一些经验,写在这里跟大家分享,我们通过例子来详细解释一 ...

  3. 【python深入】dict和list实现排序:sorted()和lambda的使用

    Python中经常需要对dict中的key值或者value值进行排序,可以通过sorted方法和lambda结合使用,接下来就是sorted()和lambda 一.sorted()和lambda so ...

  4. 解决:File "/usr/lib/python2.7/site-packages/more_itertools/more.py", line 340 def _collate(*iterables, key=lambda a: a, reverse=False): 的报错

    cyberb commented on 15 Apr Traceback (most recent call last): File "/snap/users/x1/python/bin/l ...

  5. Python的函数式编程: map, reduce, sorted, filter, lambda

    Python的函数式编程 摘录: Python对函数式编程提供部分支持.由于Python允许使用变量,因此,Python不是纯函数式编程语言. 函数是Python内建支持的一种封装,我们通过把大段代码 ...

  6. python学习 -- operator.itemgetter(), list.sort/sorted 以及lambda函数

    Python 中有非常方便高效的排序函数,下面主要介绍如何sort/sorted对list,dict进行排序. 1. 用list.sort /sorted 对list of tuples中第二个值进行 ...

  7. python-文件字符分布【get()函数与.sort(key=lambda x:x[0],reverse = False)】

    文件字符分布 描述 统计附件文件的小写字母a-z的字符分布,即出现a-z字符的数量,并输出结果.‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬ ...

  8. (05)odoo数据库和业务操作

    以一个例子开头* To-do 向导   # 配置文件       __openerp_.py:         { 'name': 'To-do Tasks Management Assistant' ...

  9. (03)odoo模型/记录集/公用操作

    -----------------更新时间11:17 2016-09-18 星期日11:00 2016-03-13 星期日09:10 2016-03-03 星期四11:46 2016-02-25 星期 ...

随机推荐

  1. 获取系统的documents路径

    获取路径 https://superuser.com/questions/1132288/windows-command-prompt-get-relocated-users-documents-fo ...

  2. mysql主从架构,IO、SQL线程运行为YES,从库没有同步数据

    mysql基于binlog主从复制架构,IO.SQL线程运行为YES,从库没有同步数据 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_D ...

  3. day40—JavaScript多物体运动框架

    转行学开发,代码100天——2018-04-25 今天继续学习JavaScript的运动实现——多物体运动框架的介绍及其应用. 首先来看一个简单的例子.如下图,要使图中3个红色盒子实现鼠标移入变宽,移 ...

  4. php面向对象三大特性

    1.封装: 目的:使类更加安全 步骤:1.成员变量变成private(私有的)2.设置方法/调用方法3.在方法中增加限制 <?php class shao { private $aa;//必须是 ...

  5. Vagrant 手册之 Vagrantfile - 机器设置 config.vm

    原文地址 配置的命名空间:config.vm config.vm 中的设置修改 Vagrant 管理的机器的配置. 1. 可用的设置项 config.vm.boot_timeout Vagrant 等 ...

  6. JSP中四种属性保存范围(1)

    一.四种属性范围 在JSP中提供了四种属性保存范围 page:在一个页面内保存属性,跳转之后无效request:在一次服务请求范围内,服务器跳转后依然有效session:-在一次会话范围内,无论何种跳 ...

  7. 【FICO系列】SAP 创建会计凭证(FB01)的BAPI

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP 创建会计凭证(FB01) ...

  8. Mac002--Git安装

    Mac--Git安装 注意:在安装Git前,可先安装homebrew,应用brew命令安装Git即可. 一.Mac 安装homebrew 参考博客:https://blog.csdn.net/yuex ...

  9. javaScript Map

                  }                   } }                          vertices.push(v);         adjList.set ...

  10. 《JAVA设计模式》之备忘录模式(Memento)

    在阎宏博士的<JAVA与模式>一书中开头是这样描述备忘录(Memento)模式的: 备忘录模式又叫做快照模式(Snapshot Pattern)或Token模式,是对象的行为模式. 备忘录 ...