我想了解Python字典上max函数的操作。以下是我使用的代码:了解Python字典上的最大功能操作
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:
tall_buildings.values()
给出高度流max
函数返回高度的最大值。2:
tall_buildings.items()
给出的(名字,高度)对流和max函数返回基于key=pair's height.
一对不过,我很难理解如何# 3
作品。 key=tall_buildings.get
如何成为寻找最高建筑物的关键?
我已经采取了代码Ned的PYCON讲座:https://youtu.be/EnSu9hHGq5o?t=12m42s
dict.get方法接受一个键并返回相关的值。因此,max函数将会遍历字典中的所有条目,并将该对与最大高度关联起来。 – user452570