[英]Using a lambda with sorted function
I came across the following code and it is working fine.Though I looked for lambda functions in other questions , but did not find a relevant answer 我遇到了以下代码,并且运行良好。尽管我在其他问题中寻找了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}]
Questions: 问题:
Well, let's try it: 好吧,让我们尝试一下:
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)
which produces 产生
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
Conclusion: the key function is called once per item being sorted. 结论:每个被排序的项都调用一次关键函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.