python中max函数用法_了解Python字典上的max函数操作

本文详细解释了Python字典中max函数的三种用法。通过示例代码,展示了如何找出最高建筑的高度(#1),获取最高建筑的名称和高度对(#2),以及直接获取最高建筑的名称(#3)。对于#3,max函数结合key参数和字典的get方法,依据建筑高度找出最高建筑的键。
摘要由CSDN通过智能技术生成

我想了解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和#2的工作原理.

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如何用作找到最高建筑物的钥匙?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值