从 Python 元组列表中获取第 N 列的最大值
当需要从元组列表中获取第“N”列的最大值时,可以使用列表解析和“max”方法来完成。
列表解析是一种在列表中进行迭代并对其执行操作的速记方法。“max”方法返回可迭代对象中值的最大值。
列表可用于存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。
元组列表基本上包含一个列表中的元组。
以下是这方面的演示例子 −
示例
my_list = [( 67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)]
print ("The list is : " )
print(my_list)
N = 2
print("The value of 'N' has been initialized")
my_result = max([sub[N] for sub in my_list])
print("The maximum of Nth column in the list of tuples is : " )
print(my_result)输出
The list is : [(67, 78, 39), (34, 23, 52), (99, 69, 78), (2, 11, 0)] The value of 'N' has been initialized The maximum of Nth column in the list of tuples is : 78
说明
- 定义了一个元组列表,并在控制台上显示。
- 初始化“N”的值。
- 使用列表解析遍历元组列表,并使用“max”方法从元组列表中获取最大值。
- 将此操作分配给一个变量。
- 该变量是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP