文章背景:pythontutorial3文档中提到了Lambda形式。里面提及,Lambda的一个用途是将一个小函数作为参数传递:
代码语言:javascript复制>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
对于pairs.sort(key=lambda pair: pair[1])
,以及sort之后的结果,一开始没看明白。后来在stackoverflow上找到了详细的解答。要理解这一问题,需要分别对sort method, key function和lambda有个基本了解。
- sort() method
Python lists have a built-in
sort()
method that modifies the list in-place and asorted()
built-in function that builds a new sorted list from an iterable.list.sort()
method is only defined for lists. In contrast, thesorted()
function accepts any iterable.
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
代码语言:javascript复制>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]
- Key functions
Starting with Python 2.4, both
list.sort()
andsorted()
added akey
parameter to specify a function to be called on each list element prior to making comparisons.
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
The value of the key
parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
- Lambda匿名函数 匿名函数lambda:是指一类无需定义标识符(函数名)的函数或子程序。 lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。 lambda匿名函数的格式:冒号前是参数,可以有多个,用逗号隔开,冒号右边的为表达式。其实lambda返回值是一个函数的地址,也就是函数对象。
a=lambda x:x*x
print(a)
print(a(3))
---->
<function <lambda> at 0x0000000002093E18>
9
- 回到最初的问题
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
此处,pairs是一个列表(list),列表中的元素是元组(tuple)。通过key: lambda
对pairs进行重新排序。lambda pair: pair[1],依据元组中的第2项(字符串)进行排序(默认是升序)。即four,one,three,two。所以pairs经过sort后,变为[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
。
参考资料:
- Lambda形式(https://ddz.red/jmGgh)
- Syntax behind sorted(key=lambda: …)(https://ddz.red/FgnM6)
- Sorting Mini-HOW TO(https://ddz.red/pIE2w)
- python中的lambda函数用法(https://ddz.red/VepMF)