在Python字典上理解max函数操作

2024-03-29 06:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解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 and max 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 the key=pair's height.

但是,我很难理解# 3是如何工作的。如何将key=tall_buildings.get作为找到最高建筑的关键?在

我从内德的Pycon谈话中得到了代码:https://youtu.be/EnSu9hHGq5o?t=12m42s


Tags: ofthekey代码namefindmaxvalues
3条回答

3的工作方式是,作为key提供的方法将简单地从tall_buildings字典中查找值。因此,对于每个被迭代的key,相应的{}将由{}提供。在

get方法与[]运算符同义

>>> tall_buildings['Sears Tower']
442
>>> tall_buildings.get('Sears Tower')
442

首先,3是在键上循环的原因是,默认情况下,迭代一个dict只会循环到键上

^{pr2}$

也可以显式地循环键

for i in tall_buildings.keys():
    print(i)

Taipei 101
Empire State
Burj Khalifa
Sears Tower

类似地,您可以循环.values(),它只是字典中的值,或者{}循环(key,value)对的元组。在

max()函数在其第一个参数上迭代,将key函数应用于每个项,并选择具有最大键的项。在

迭代字典与迭代其键是一样的。执行时

max(tall_buildings, key=tall_buildings.get)

我们将首先迭代tall_buildings中的所有键。对于每个键k,将对键函数tall_buildings.get(k)求值,该函数返回用k表示的建筑高度。然后选择并返回具有最大高度的k。在

max的概念需要一个项目的排序的定义。在

所以这里您提供了key参数,就像您对sort所做的一样:一个应用于字典的每个元素的函数,以便将(key, val)对映射到具有内置顺序定义(例如数字、字符串)的值。因此,您将找到映射的值的最大值,结果将是原始字典中相应的元素。在

相关问题 更多 >