Python|在给定的嵌套列表中查找具有最大值的子列表
给定一个列表列表,任务是在第二列中找到最大值的子列表。
例子:
Input : [['Paras', 90], ['Jain', 32], ['Geeks', 120],
['for', 338], ['Labs', 532]]
Output :['Labs', 532]
Input: [['Geek', 90], ['For', 32], ['Geeks', 120]]
Output: ['Geeks', 120]
以下是实现上述任务的一些任务。
方法 #1:使用 lambda
# Python code to find maximum value
# in second column of list of list
# Input list initialization
Input = [['Paras', 90], ['Jain', 32], ['Geeks', 120],
['for', 338], ['Labs', 532]]
# Using lambda
Output = max(Input, key = lambda x: x[1])
# printing output
print("Input List is :", Input)
print("Output list is : ", Output)
输出:
Input List is : [[‘Paras’, 90], [‘Jain’, 32], [‘Geeks’, 120], [‘for’, 338], [‘Labs’, 532]]
Output list is : [‘Labs’, 532]
方法 #2:使用 itemgetter
# Python code to find maximum value
# in second column of list of list
# Importing
import operator
# Input list initialization
Input = [['Paras', 90], ['Jain', 32], ['Geeks', 120],
['for', 338], ['Labs', 532]]
# Using itemgetter
Output = max(Input, key = operator.itemgetter(1))
# Printing output
print("Input List is :", Input)
print("Output list is : ", Output)
输出:
Input List is : [[‘Paras’, 90], [‘Jain’, 32], [‘Geeks’, 120], [‘for’, 338], [‘Labs’, 532]]
Output list is : [‘Labs’, 532]