我试图理解Python字典中max函数的操作。我正在使用以下代码:
tall_buildings = {
"Empire State": 381, "Sears Tower": 442,
"Burj Khalifa": 828, "Taipei 101": 509
}
# 1. find the height of the tallest building
print("Height of the tallest building: ", max(tall_buildings.values()))
# 2. find the name, height pair that is tallest
print(max(tall_buildings.items(), key=lambda b: b[1]))
# 3. find the tallest building
print(max(tall_buildings, key=tall_buildings.get))
上面所有的打印语句都给出了正确的结果,如代码中的注释所示。在
我了解#1
和{
1:
tall_buildings.values()
gives a stream of heights andmax
function returns the max of the heights.2:
tall_buildings.items()
gives a stream of (name, height) pairs and max function returns the pair based on thekey=pair's height.
但是,我很难理解# 3
是如何工作的。如何将key=tall_buildings.get
作为找到最高建筑的关键?在
我从内德的Pycon谈话中得到了代码:https://youtu.be/EnSu9hHGq5o?t=12m42s
3的工作方式是,作为}将由{}提供。在
key
提供的方法将简单地从tall_buildings
字典中查找值。因此,对于每个被迭代的key
,相应的{get
方法与[]
运算符同义首先,3是在键上循环的原因是,默认情况下,迭代一个
^{pr2}$dict
只会循环到键上也可以显式地循环键
类似地,您可以循环}循环
.values()
,它只是字典中的值,或者{(key,value)
对的元组。在max()
函数在其第一个参数上迭代,将key函数应用于每个项,并选择具有最大键的项。在迭代字典与迭代其键是一样的。执行时
我们将首先迭代
tall_buildings
中的所有键。对于每个键k
,将对键函数tall_buildings.get(k)
求值,该函数返回用k
表示的建筑高度。然后选择并返回具有最大高度的k
。在max的概念需要一个项目的排序的定义。在
所以这里您提供了
key
参数,就像您对sort所做的一样:一个应用于字典的每个元素的函数,以便将(key, val)
对映射到具有内置顺序定义(例如数字、字符串)的值。因此,您将找到映射的值的最大值,结果将是原始字典中相应的元素。在相关问题 更多 >
编程相关推荐