简体   繁体   English

为什么Python中的min()在字典上使用lambda时返回密钥?

[英]Why does min() in Python return the key when a lambda is used on dictionaries?

I am studying the Python Cookbook, 3rd edition. 我正在研究Python Cookbook,第3版。 I encountered the code below: 我遇到了以下代码:

prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}

min(prices, key=lambda k: prices[k])

I tested this on Python 3.6.0, and it returns 'FB'. 我在Python 3.6.0上测试了它,它返回'FB'。

My understanding is that every key from the prices dictionary is sent to the lambda as parameter k and then the lambda returns the value associated with key k in the prices dictionary. 我的理解是, prices字典中的每个键都作为参数k发送到lambda,然后lambda返回prices字典中与键k相关联的值。 So after iterating through all the keys, a list of values is returned which is used as an argument to the min function which finally returns the minimum value (in this case 10.75) in the dictionary. 因此,在遍历所有键之后,返回值列表,该列表用作min函数的参数,该函数最终返回字典中的最小值(在本例中为10.75)。

But when I ran the code, the program printed out the key (in this case 'FB'). 但是当我运行代码时,程序打印出密钥(在本例中为“FB”)。 Where am I wrong? 我哪里错了?

I have gone through the documentation. 我已经完成了文档。 It said min returns the smallest item in an iterable. 它表示min返回可迭代中的最小项。 I know min processes the keys and not the values. 我知道min处理键而不是值。 I just don't understand how it returns the key when the lambda returns a list of values. 我只是不明白当lambda返回值列表时它是如何返回键的。 Help me please. 请帮帮我。

EDIT : Sorry for the edit. 编辑 :抱歉编辑。 I am trying to find the key of the smallest value in the dictionary. 我试图找到字典中最小值的关键。 The above code works perfectly but I don't know how it works. 上面的代码完美无缺,但我不知道它是如何工作的。

You are correct that the lambda function you defined will be applied to all the keys, however that does not mean that min will return whatever your lambda function may return. 你定义的lambda函数将应用于所有键是正确的,但这并不意味着min将返回lambda函数可能返回的任何内容。

Perhaps it's helpful to spell out the line 也许拼出这条线很有帮助

min(prices, key=lambda k: prices[k])

in words: 用语言:

"Find the minimum of the iterable prices (the dictionary keys 1 ), as if each key k had the value prices[k] ." “找到可迭代prices的最小值(字典键1 ), 就像每个键k具有价值prices[k] 。”

If you want the associated value, you can use the returned key to access prices 如果需要关联值,可以使用返回的密钥来访问prices

>>> prices[min(prices, key=lambda k: prices[k])]
>>> 10.75

or much shorter: 或者更短:

>>> min(prices.values())
>>> 10.75

1 Because a dictionary is an iterable of keys ( list(prices) gives a list of keys). 1因为字典是可迭代的键( list(prices)给出了键列表)。

why min() in python returns key when lambda is used on dictionaries 为什么在字典中使用lambda时python中的min()返回键

Because iterating dictionaries iterates over the keys in arbitrary order. 因为迭代字典以任意顺序迭代键。 The key parameter is NOT a map parameter. key参数不是map参数。

If you want the minimum value, then take min(prices.items()) min(prices.values()) . 如果你想要最小值,那么取 min(prices.items()) min(prices.values())

When you iterate through a dictionary (as you are doing implicitly with min() ), it uses the keys. 当您遍历字典时(正如您使用min()隐式执行),它使用键。 min(prices) is equivalent to min(prices.keys()) . min(prices)相当于min(prices.keys()) So min() iterates through each of the KEYS in the dictionary, and uses the lambda function to compare them. 所以min()遍历字典中的每个KEYS,并使用lambda函数来比较它们。 It returns one of the items in what it is iterating over - so one of the keys. 它返回迭代的项目之一 - 所以其中一个键。

If you want the items instead, you can use min(prices.items()) , no key needed. 如果你想要这些项目,你可以使用min(prices.items()) ,不需要密钥。

If you want both, I would just use what you have an get the price with the returned key. 如果你想要两者,我会用你所拥有的东西来获得返回键的价格。

The thing you supply as key is merely used to sort the iterable you give it - in your case all the keys of the dictionary - you get "the one" returned that is lowest according to your key-definition . 你提供的key仅用于对你给出的迭代进行排序 - 在你的情况下,字典的所有键 - 根据你的key-definition你得到的“一个”是最低的。

Example: 例:

data = ["a","bb","ccc","dddd"]

print( min( data, key = lambda x: -len(x))) # get the min value by negative length ascending

Prints: 打印:

dddd

because the elements of the list got evaluated according to theire respective negative length: 因为列表的元素是根据各自的负长度进行评估的:

['a', 'bb', 'ccc', 'dddd']  # iterable
[ -1,  -2 ,   -3,     -4 ]  # the key-result

and the minimal ones from the iterable was returned: 'dddd' 并且返回了iterable中的最小值: 'dddd'

If you want both the key and the value, you can use: 如果你想要键值,你可以使用:

>>> min(prices.items(), key=lambda kv: kv[1])
('FB', 10.75)

min returns the smallest item of an iterable. min返回可迭代的最小项。 To decide what elements are smaller, it uses the key. 要确定哪些元素较小,它会使用密钥。 Here, you're asking for the minimum of prices , so it returns the smallest element of that iterable. 在这里,您要求的是最低prices ,因此它返回该可迭代的最小元素。 The key just tells min to use that key in deciding which items of the iterable are smaller; 密钥告诉min使用该密钥来决定迭代的哪些项目较小; min still uses the values of the iterable, not the key applied to the values, as the minimum to return. min仍然使用iterable的值,而不是应用于值的键,作为返回的最小值。 Imagine if someone says "Tell me what country is largest by population". 想象一下,如果有人说“告诉我哪个国家的人口最多”。 The correct answer is "China", not 1.386 billion. 正确的答案是“中国”,而不是13.86亿。 1.386 billion is the value used to decide that China is "largest", not the thing that is largest. 1.386十亿是用来决定,中国是“最大的”,不就是最大的事情的价值。 When you write min(iterable, key=key) , you are asking for the smallest of iterable by key , not the smallest key . 当你写min(iterable, key=key) ,你要求key最小的iterable ,而不是最小的key Basically, min is equivalent to the following: 基本上, min相当于以下内容:

 def min(iterable, key = lambda x:x):
      cur_min = iterable.first
      for item in iterable:
            if key(item)<key(cur_min):
                 cur_min = item
     return cur_min

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带lambda的min总是返回python中的第一个值吗? - Does min with lambda always return the first value in python? 与python一起使用时,mysql为什么返回(&#39;abc&#39;)格式的字符串 - Why does mysql return string in format of ('abc') when used with python 为什么这个 min() 调用适用于字典 - Why does this min() call work for dictionaries 在 Python 中用作返回类型时,Ellipses 是什么意思,为什么要使用它? - What does Ellipses mean when used as the return type in Python, and why use it? min(iterable, *[, key, default]) 返回什么 - What does min(iterable, *[, key, default]) return Python Lambda比较字典 - Python Lambda Comparing Dictionaries 为什么这个关于字典的 Python 片段有效? - Why does this Python snippet regarding dictionaries work? Python词典:为什么以及何时必须在键和值之间使用有时“:”和有时“ =”? - Python dictionaries: why and when I have to use sometimes “:” and sometimes “=” between the key and the value? 为什么python mock.patch在使用第二个补丁参数vs return_value时工作方式不同? - Why does python mock.patch work differently when second patch argument is used vs return_value? python(ubuntu 16.04.1上的2.7.12版)-函数(类似于返回元素2的lambda)不能用作排序的键 - python (version 2.7.12 on ubuntu 16.04.1) - a function (similar to a lambda to return element 2) does not work as a key to sorted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM