比较嵌套列表中的索引

2024-05-21 00:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个列表[['apple', 'tree', 4, 5], ['orange', 'bush', 6, 3]]。并不总是有两个嵌套列表,可能更多。我知道如何比较这个特定列表中的索引2,但是假设有6个嵌套列表。你知道吗

如何比较所有索引中的索引2,然后在第二个索引中存储值最大的列表。关键是我不知道有多少名单,需要让它工作的任何数额。子列表的长度都相同,并且第二个索引将包含一个整数,这是一个先决条件。你知道吗

这是学校的一个问题,所以我只需要基本想法的帮助,而不是整个代码块,因为我不想抄袭。我已经尝试过了,但是我得到了索引超出范围的错误。任何帮助都将不胜感激

temp = []
for i in range(len(lst)):
    if lst[i][2] > lst[i+1][2]:
        temp = lst[i]
return temp    `

Tags: 代码treeapple列表先决条件整数temp学校
3条回答

lst=[[“苹果”,“树”,4,5],[“橘子”,“灌木”,6,3],[“aa”,“bb”,2,3]]

print max(lst, key=lambda x:x[2])

或者

temp = lst[0]
for i in range(len(lst)):
    temp = temp if temp[2] > lst[i][2] else lst[i]
print temp

output: ['orange', 'bush', 6, 3]

通过指定key to max函数,我们可以实现这一点 这里的键是列表中的第二个元素。因此,将key=lambda l:l[2]添加到正规max函数就是解决这个问题的方法

>>> max( lst ,key=lambda l :l[2])
['orange', 'bush', 6, 3]
>>> 

阅读这篇文章了解更多关于如何使用和使用的优点的细节密钥:lambdaWhat is key=lambda

只需在max中使用key参数即可:

s = [['apple', 'tree', 4, 5], ['orange', 'bush', 6, 3]]
new_s = max(s, key=lambda x:x[2])

输出:

['orange', 'bush', 6, 3]

关于现在的代码,您需要将lst[0]分配给temp,以便为您的算法提供一个基准:

def the_max(lst):
   temp = lst[0] #use lst[0] as the first benchmark.
   for i in range(len(lst)):
      if lst[i][2] > temp[2]:
         temp = lst[i]
   return temp

相关问题 更多 >