Syntax behind sorted(key=lambda :)
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.
- 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.
- 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 :)的更多相关文章
- python3排序 sorted(key=lambda)--实现对字典按value值排序
使用python对列表(list)进行排序,说简单也简单,说复杂也复杂,我一开始学的时候也搞不懂在说什么,只能搜索一些英文文章看看讲解,现在积累了一些经验,写在这里跟大家分享, 1.sorted函数首 ...
- python3排序 sorted(key=lambda)
使用python对列表(list)进行排序,说简单也简单,说复杂也复杂,我一开始学的时候也搞不懂在说什么,只能搜索一些英文文章看看讲解,现在积累了一些经验,写在这里跟大家分享,我们通过例子来详细解释一 ...
- 【python深入】dict和list实现排序:sorted()和lambda的使用
Python中经常需要对dict中的key值或者value值进行排序,可以通过sorted方法和lambda结合使用,接下来就是sorted()和lambda 一.sorted()和lambda so ...
- 解决: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 ...
- Python的函数式编程: map, reduce, sorted, filter, lambda
Python的函数式编程 摘录: Python对函数式编程提供部分支持.由于Python允许使用变量,因此,Python不是纯函数式编程语言. 函数是Python内建支持的一种封装,我们通过把大段代码 ...
- python学习 -- operator.itemgetter(), list.sort/sorted 以及lambda函数
Python 中有非常方便高效的排序函数,下面主要介绍如何sort/sorted对list,dict进行排序. 1. 用list.sort /sorted 对list of tuples中第二个值进行 ...
- python-文件字符分布【get()函数与.sort(key=lambda x:x[0],reverse = False)】
文件字符分布 描述 统计附件文件的小写字母a-z的字符分布,即出现a-z字符的数量,并输出结果. ...
- (05)odoo数据库和业务操作
以一个例子开头* To-do 向导 # 配置文件 __openerp_.py: { 'name': 'To-do Tasks Management Assistant' ...
- (03)odoo模型/记录集/公用操作
-----------------更新时间11:17 2016-09-18 星期日11:00 2016-03-13 星期日09:10 2016-03-03 星期四11:46 2016-02-25 星期 ...
随机推荐
- (转)原理到实现 | K8S 存储之 NFS
转:https://mp.weixin.qq.com/s/Mrr1Rnl_594Gyyn9fHekjw 1NFS介绍 NFS是Network File System的简写,即网络文件系统,NFS是Fr ...
- 如何修改运行中的docker容器的端口映射
在docker run创建并运行容器的时候,可以通过-p指定端口映射规则.但是,我们经常会遇到刚开始忘记设置端口映射或者设置错了需要修改.当docker start运行容器后并没有提供一个-p选项或设 ...
- nginx配置-main
nginx配置分为几大块: main (全局设置) events(nginx工作模式) http(http设置): upstream(负载均衡服务器设置),server(主机设置):location( ...
- C#-概念-基础类库:基础类库
ylbtech-C#-概念-基础类库:基础类库 基础类库 (BCL) 是微软所提出的一组标准库可提供.NET Framework所有语言使用. 随着 Windows 以及 .NET Framework ...
- leetcode 88. C++ 合并两个有序数组
Leetcode 88. 合并两个有序数组 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组. 说明: 初始化 nums1 和 ...
- delphi 牛逼 了 app (已在软件界掀起波澜)10分钟10行代码做出让人惊叹的程序
(已在软件界掀起波澜)10分钟10行代码做出让人惊叹的程序 http://v.qq.com/x/page/m0328h73bs7.html?ptag=bbs_csdn_net
- Altium Designer chapter5总结
PCB设计环境中需要注意的如下: (1)PCB设计步骤:绘制原理图和生成网表—规划电路板—载入网表—元件布局—制定设计规则—布线—后期处理—DRC检查—信号完整性分析—gerbera文件输出 (2)P ...
- webStom常用快捷键备忘
Ctrl+W 选中代码,连续按会有其他效果 Ctrl+/ 或 Ctrl+Shift+/ 注释(// 或者/…/ ) Ctrl+X 删除行Ctrl+D 复制行 ctrl+shift+ 箭头 上下移动块代 ...
- Python科学计算三维可视化(整理完结)
中国MOOC<Pyhton计算计算三维可视化>总结 课程url:here ,教师:黄天宇,嵩天 下文的图片和问题,答案都是从eclipse和上完课后总结的,转载请声明. Python数据三 ...
- C# 栈=>随时读取栈中最小值
//原理:利用两个栈,一个记录最小值,一个记录数据. using System; using System.Collections.Generic; using System.Linq; using ...