我遇到了以下代码并且工作正常。虽然我在其他问题中查找了lambda函数,但没有找到相关答案
In[9]: portfolio=[
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'IAM', 'shares': 100, 'price': 41.1},
{'name': 'IBM', 'shares': 100, 'price': 71.1} ,
{'name': 'IBM', 'shares': 100, 'price': 31.1}
]
In [10]: s = sorted(portfolio,key = lambda s : s['price'] )
Out[10]: s
[{'name': 'IBM', 'price': 31.1, 'shares': 100},
{'name': 'IAM', 'price': 41.1, 'shares': 100},
{'name': 'IBM', 'price': 71.1, 'shares': 100},
{'name': 'IBM', 'price': 91.1, 'shares': 100}]
问题:
答案 0 :(得分:2)
好吧,试试吧:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'IAM', 'shares': 100, 'price': 41.1},
{'name': 'IBM', 'shares': 100, 'price': 71.1} ,
{'name': 'IBM', 'shares': 100, 'price': 31.1}
]
def key_fn(s):
print("called key_fn({}) -> {}".format(s, s['price']))
return s['price']
s = sorted(portfolio, key=key_fn)
产生
called key_fn({'shares': 100, 'price': 91.1, 'name': 'IBM'}) -> 91.1
called key_fn({'shares': 100, 'price': 41.1, 'name': 'IAM'}) -> 41.1
called key_fn({'shares': 100, 'price': 71.1, 'name': 'IBM'}) -> 71.1
called key_fn({'shares': 100, 'price': 31.1, 'name': 'IBM'}) -> 31.1
结论:每个要排序的项目都会调用一次关键函数。