在Python中的元组列表中获取具有最大值的第一个元素

我们有一个元组列表。我们需要找出其中最大的元组。但是,如果多个元组具有相同的值,我们需要第一个具有最大值的元组。

使用itemgetter和max

使用itemgetter(1),我们从索引位置1获得所有值,然后应用max函数获得具有最大值的项目。但是,如果返回的结果不止一个,我们应用索引零以获取其中包含最大元素的第一个元组。

示例

from operator import itemgetter
# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using max() and itemgetter()res = max(listA, key=itemgetter(1))[0]
# printing result
print("Day with maximum score is : \n",res)

输出结果

运行上面的代码给我们以下结果-

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue

带有max和lambda

我们使用lambda函数将元素移到索引位置1,然后应用max函数。然后,将索引位置0应用于多个匹配项中的第一个以获取最终结果。

示例

# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using max() and lambda
res = max(listA, key = lambda i : i[1])[0]
# printing result
print("Day with maximum score is : \n",res)

输出结果

运行上面的代码给我们以下结果-

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue

带排序

在这种方法中,当应用lambda函数时,我们使用排序条件函数,其条件等于真实条件。

示例

# initializing list
listA = [('Mon', 3), ('Tue', 20), ('Wed', 9)]
# Given list
print("Given list : \n" ,listA)
# using sorted() and lambda
res = sorted(listA, key = lambda i: i[1], reverse = True)[0][0]
# printing result
print("Day with maximum score is : \n",res)

输出结果

运行上面的代码给我们以下结果-

Given list :
[('Mon', 3), ('Tue', 20), ('Wed', 9)]
Day with maximum score is :
Tue