引子:在《Python CookBook》一书的1.4章节中出现了一下代码:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
见到这段代码,我的第一反应是“什么鬼?”,我知道nlargest()和nsmallest()除了前两个参数外,还接收一个关键字参数,用于复杂数据结构(其实就是字典),指定按照那个变量的值来排序,但是这lambda是什么东西,难道不应该是