简体   繁体   中英

How to get item from previous list in a list of lists in Python?

I have a list of lists and another list like this:

new_list = []

lst_of_lst = [['MHK', 549, 'ABC', 3], ['OMK', 567, 'TTT', 8], ['KDH', 675, 'TGH' , 12]]
lst = ['MHK', 553, 'ABC']

I have to observe when lst_of_lst[1] is grater than lst[1] and then "go back" to the previous list to get lst_of_lst[3] , in this case "3", because 553 (from lst) is between 549 and 567. 3 should afterwards be appended to new_list , but this is not a problem.

I have tried with:

if lst_of_lst[1] > lst[1]:
    new_list.append(lst_of_lst[3][:-1])

But this does not work. To be more specific: How should the append look like to get the number from the last list in lst_of_lst that is not grater than list[1]. Hope you understand my question.

Can someone help me out? Thanks in advance.

To point out what's wrong with your solution -

  • lst_of_lst[1] > lst[1] - here you compare a list to a value, which will give you a TypeError.
  • You're trying to append an element that doesn't exist - lst_of_lst[3][:-1] - lst_of_lst[3] is out of range, the index only goes 0,1,2. Finally, [:-1] sets a range of elements up to the last one, not the last value.

Your question is very obscure since it is not clear what you want to do exactly to be able to generalise the solution, ie go iteratively over all elements) - otherwise you can just do this manually. To specifically answer your question you should try this

new_lst = [] if lst_of_lst[1][1] > lst[1]: new_lst.append(lst_of_lst[0][-1])

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