Home > Software engineering >  Removing specific nested lists from a whole list [closed]
Removing specific nested lists from a whole list [closed]

Time:10-02

I have a nested list like this in python

[['NS1259', 163, 8.38, 268],
 ['NS6969', 88, 15.7, 620],
 ['NS4722', 155, 10.02, 343],
 ['NS3629', 150, 5.4, 530]]

I want to create a function to remove any one nested list from the whole list by using the value in the first string. So using N6969 it would end up like this

[['NS1259', 163, 8.38, 268],
 ['NS4722', 155, 10.02, 343],
 ['NS3629', 150, 5.4, 530]]

CodePudding user response:

As you want a function, here is an example with a list comprehension:

def filteritem(iterable, element):
    return [i for i in iterable if i[0] != element]

example:

l = [['NS1259', 163, 8.38, 268],
     ['NS6969', 88, 15.7, 620],
     ['NS4722', 155, 10.02, 343],
     ['NS3629', 150, 5.4, 530]]

new_list = filteritem(l, 'NS6969') # outputs a new list without the 'NS6969' line

You could also use filter instead of a comprehension:

list(filter(lambda x: x[0]!= 'NS6969', l))

CodePudding user response:

You could use this:

big_list = [
    ['NS1259', 163, 8.38, 268],
    ['NS6969', 88, 15.7, 620],
    ['NS4722', 155, 10.02, 343],
    ['NS3629', 150, 5.4, 530]
]
for i in range(len(big_list)-1, -1, -1):
    if big_list[i][0] == 'NS6969':
        del big_list[i]

This works from the end to the start, to avoid losing track of your place in the list when you delete an item. If you are sure there will only be one item with this key, then you could iterate forward and add break after deleting the item. But in that case you may be better off using a dictionary instead of a list.

Another option would be to create a new list each time:

big_list = [x for x in big_list if x[0] != 'NS6969']
  • Related