简体   繁体   中英

comparing indexes in a nested list

Suppose I have a list [['apple', 'tree', 4, 5], ['orange', 'bush', 6, 3]] . There isn't always 2 nested lists, could be more. I know how I would compare indexes 2 from this specific list, but lets say there's 6 nested lists.

How would I compare index 2 in all of them, and then store the list with the largest value in its second index. The point is I don't know how many lists there are and need to make it work for any amount. There is a precondition and its that the sublists are all the same length and that the second index will contain an integer.

This is a question for school so I just need help with the basic idea and not really the whole chunk of code as I don't want to plagiarize. I have made attempts, but I get index out of range error. Any help would be appreciated

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

You can just use the key parameter in max :

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

Output:

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

Regarding your code now, you will want to assign lst[0] to temp to give your algorithm a benchmark to start with:

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

by specifying key to max function , we can achieve this Here key is second element in list. So adding key=lambda l:l[2] to the normal max function is the solution for this

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

Read this post for more details on how to use and advantages of using key:lambda What is key=lambda

lst = [['apple', 'tree', 4, 5], ['orange', 'bush', 6, 3],['aa', 'bb', 2, 3]]

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

or

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM