📌  相关文章
📜  Python|获取元组列表中具有最大值的第一个元素

📅  最后修改于: 2022-05-13 01:54:25.174000             🧑  作者: Mango

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

在Python中,我们可以以元组的形式绑定结构信息,然后可以检索相同的信息。但有时我们需要其他元组索引的最大值对应的元组信息。此功能有许多应用程序,例如排名。让我们讨论一些可以实现这一目标的方法。

方法 #1:使用max() + operator.itemgetter()
我们可以使用提供的键 itemgetter 索引从列表中获取对应元组索引的最大值,然后在最后使用索引规范提及所需的索引信息。

# Python3 code to demonstrate 
# to get tuple info. of maximum value tuple
# using max() + itemgetter()
from operator import itemgetter
  
# initializing list 
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
  
# printing original list 
print ("Original list : " + str(test_list))
  
# using max() + itemgetter()
# to get tuple info. of maximum value tuple
res = max(test_list, key = itemgetter(1))[0]
  
# printing result
print ("The name with maximum score is : " + res)
输出:
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet


方法 #2:使用max() + lambda
该方法与上面讨论的方法几乎相似,不同之处在于最大值的目标元组索引的规范和处理是由 lambda函数完成的。这提高了代码的可读性。

# Python3 code to demonstrate 
# to get tuple info. of maximum value tuple
# using max() + lambda
  
# initializing list 
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
  
# printing original list 
print ("Original list : " + str(test_list))
  
# using max() + lambda
# to get tuple info. of maximum value tuple
res = max(test_list, key = lambda i : i[1])[0]
  
# printing result
print ("The name with maximum score is : " + res)
输出:
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet


方法 #3:使用sorted() + lambda
上述两种方法中max()执行的任务可以通过反向排序和打印第一个元素来完成。 lambda函数执行类似于上述方法的任务。

# Python3 code to demonstrate 
# to get tuple info. of maximum value tuple
# using sorted() + lambda
  
# initializing list 
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
  
# printing original list 
print ("Original list : " + str(test_list))
  
# using sorted() + lambda
# to get tuple info. of maximum value tuple
res = sorted(test_list, key = lambda i: i[1], reverse = True)[0][0]
  
# printing result
print ("The name with maximum score is : " + res)
输出:
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet