理解Python字典上的max函数操作
我正在努力理解Python字典中max函数的操作。以下是我正在使用的代码:理解Python字典上的max函数操作,python,dictionary,functional-programming,max,Python,Dictionary,Functional Programming,Max,我正在努力理解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_bui
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
和#2
的工作原理
1:toll\u buildings.values()
提供高度流,而max
函数返回高度的最大值
2:toll\u buildings.items()
给出一个(名称、高度)对流,max函数根据key=pair的高度返回该对。
然而,我很难理解#3
是如何工作的。怎样才能找到最高的建筑呢
我从Ned的Pycon Talk中获取了代码:3的工作方式是,作为键提供的方法只需从高层建筑
字典中查找值。因此,对于迭代的每个键
,相应的值将由get
提供
get
方法与[]
运算符同义
>>> tall_buildings['Sears Tower']
442
>>> tall_buildings.get('Sears Tower')
442
#3首先循环键的原因是,默认情况下,迭代dict
将只循环键
您还可以显式循环键
for i in tall_buildings.keys():
print(i)
Taipei 101
Empire State
Burj Khalifa
Sears Tower
类似地,您可以循环使用.values()
这只是字典中的值,也可以循环使用.items()
这两个元组的(键,值)
对。函数对其第一个参数进行迭代,将键函数应用于每个项,并选择具有最大键的项
在字典上迭代与在其键上迭代是相同的。执行时
max(tall_buildings, key=tall_buildings.get)
我们将首先迭代高层建筑中的所有关键点。对于每个键k
将评估键功能toll\u buildings.get(k)
,它返回由k
表示的建筑物高度。然后将选择并返回具有最大高度的k
。最大高度的概念需要对项目的顺序进行定义
因此,这里您提供了key
参数,正如您所做的那样:一个应用于字典中每个元素的函数,以便将(key,val)
对映射到具有内置顺序定义(例如数字、字符串)的值。因此,您将找到映射值的最大值,结果将是原始字典中的对应元素。但我们没有给出键,是吗?@harshil9968迭代字典与迭代其键相同。是每次传递给高层建筑的参数。get,dictionary?dict.get方法的键接受一个键并返回相关值。因此,max函数将遍历字典中的所有条目,并给出与最大高度相关联的一对。
max(tall_buildings, key=tall_buildings.get)