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. 20180709-Java循环结构

    while(布尔表达式){ //循环内容} public class Test{ public static void main(String args[]){ int x = 10; while(x ...

  2. jsplumb+dragable+vue(一)

    基于vue的jsplumb,支持拖拽生成节点,节点双击展示更多信息,节点连线,删除节点,删除连线,重绘连接图,当前页面刷新连接图,根据json画连接图等功能 本章主要讲 拖拽生成节点 获取链接图的信息 ...

  3. 【Pytest】python单元测试框架pytest简介

    1.Pytest介绍 pytest是python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高.根据pytest的官方网站介绍 ...

  4. JDBC连接sql server数据库的详细步骤和代码 转

    JDBC连接sql server数据库的步骤如下: 1.加载JDBC驱动程序(只做一次): 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机), 这通过java.lang.C ...

  5. xiugai2

    <div class="myLoading"> <div class="svg-wrap"> <svg width="8 ...

  6. Hibernate入门学习笔记

    1.Hibernate是什么? 2.hibernate怎么配置? 3.SessionFactory是干什么的?有哪些方法经常用? 4.hibernate的现成的增删改查方法怎么使用?都有哪些方法?哪些 ...

  7. 修改MySQL表varchar字段的小实验

    将actor表的first_name的varchar(45) ,修改为varchar(60) [root@vhost1 ~]# mysql -uroot -p -S /mysqldata/tmp/my ...

  8. Python web自动化测试框架搭建(功能&接口)——unittest介绍

    Python UnitTest测试框架介绍 1)         TestCase:所有测试用例类继承的基本类, TestCase的实例就是测试用例 2)         TestSuite:测试套件 ...

  9. Nginx证书配置:tomcat证书jks文件转nginx证书.cet和key文件

    Nginx证书配置:tomcat证书jks文件转nginx证书.cet和key文件1.查看jks文件中的entry. keytool -list -keystore server.jks Enter ...

  10. Spring cloud 注册服务小结

    服务注册中心:Eureka.Zookeeper.Cousul.Nacos 使用RestTemplate.openFeign做服务调用,底层使用的是Ribbon. Ribbon做了负载均衡,也可以做一个 ...