我想了解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