![](/img/trans.png)
[英]Why does min() in Python return the key when a lambda is used on dictionaries?
[英]Why does this min() call work for dictionaries
我试图在字典中找到最小元素的键。
dictionary = {'a': 5, 'b': 7, 'c': 8}
我应该得到'a'作为键。
我找到了这段代码,但我不确定它是如何工作的。
def key_of_min_value(d):
print(min(d, key=d.get))
当我假设min(d, ...)
部分说它正在获取字典中的最小元素时,我对key = d.get
的含义感到困惑。
“钥匙”这个词在这里有点过分了。 传递给min
的键,即d.get
,是一个可调用的,用于在比较之前转换值。 内置的 function sorted
有一个类似的key
参数。
此“键”与指字典的键/值时使用的“键”一词无关。
因此,代码通过迭代查找字典中d.get(k)
k
的 k 来工作。
从min
的文档中:
min(arg1, arg2, *args[, key]) :
返回可迭代项中的最小项或两个或多个 arguments 中的最小项。 如果提供了一个位置参数,它应该是一个可迭代的。 返回可迭代项中的最小项。 如果提供了两个或多个位置 arguments,则返回最小的位置 arguments。
有两个可选的仅关键字 arguments。 关键参数指定一个参数排序 function 就像用于 list.sort() 的那样。 默认参数指定一个 object 如果提供的迭代为空则返回。 如果可迭代对象为空且未提供默认值,则会引发 ValueError。
重要的是要了解min
通过迭代参数进行操作并且(不指定键)返回“最低”排名值。 使用<, >, etc.
运算符进行比较。 当您将可调用对象作为key
传递时,各个元素将用作此 function 的参数。
为了进一步分解,这是(或多或少)调用min(d, key=d.get)
时发生的事情:
lowest_val = None
lowest_result = None
for item in d:
if lowest_val is None or d.get(item) < lowest_val:
lowest_val = d.get(item) # These are the elements we are comparing
lowest_result = item # But this is the element we are 'returning'
print(f"The min value (result of the callable key) is '{lowest_val}'")
print(f"The min item corresponding to the min value is '{lowest_result}'")
请注意,我们不比较每个item
,而是比较任何可调用键的结果,当item
用作参数时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.