当需要在元组列表(即元组列表)中找到最大元素时,可以使用“ max”方法和“ operator.itemgetter”方法。
itemgetter从其操作数中获取特定项目。
“ max”方法给出了可迭代变量中的最大值,该最大值作为参数传递给它。
以下是相同的演示-
from operator import itemgetter my_list = [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)] print ("The list is : ") print(my_list) my_result = max(my_list, key = itemgetter(1))[0] print ("The name that has the maximum value is : ") print(my_result)输出结果
The list is : [('Will', 23), ('Jane', 21), ('El', 24), ('Min', 101)] The name that has the maximum value is : Min
所需的库已导入。
元组列表已定义,并显示在控制台上。
“ max”方法用于遍历列表,并将键指定为列表内每个元组的第一个元素。
该结果分配给一个值。
它在控制台上显示为输出。