文章背景:pythontutorial3文档中提到了Lambda形式。里面提及,Lambda的一个用途是将一个小函数作为参数传递:
>>> 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 that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable.
list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]list.sort() and sorted() added a key 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)]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')]。
参考资料: