简体   繁体   English

使用具有排序功能的lambda

[英]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: 问题:

  1. Is lambda function called to return the price every time a dictionary element is called from the list ? 每次从列表中调用字典元素时,都会调用lambda函数来返回价格吗? lambda is called only once ? lambda仅被调用一次?
  2. If can anyone explain this whole of how the sorted works here, it will be very helpful 如果有人可以在这里解释排序方式的全部内容,那将非常有帮助

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM