Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting an entire list from list of lists

I have a list of lists as follows :

g = [
    ["a","?","?","?","?","?","?"],
    ["?","b","?","?","?","?","?"],
    ["?","?","?","?","?","?","?"]
]

I want to iterate through this list and delete the list which contains all "?", which is the last list in this list of lists. I've tried pop() , del and several other operation but nothing seems to be working so far.

Here's what I've written for this part :

for x in g:
    if x.count("?") == 6:
        g.pop(g.index(x))

It doesn't remove the list but removes one "?" from the last list. Can anyone please guide me here.

like image 692
Shekhar Tanwar Avatar asked Jan 27 '23 21:01

Shekhar Tanwar


1 Answers

You should leverage set here:

In [152]: X = [["a","?","?","?","?","?","?"],["?","b","?","?","?","?","?"],["?","?","?","?","?","?","?"]]

In [153]: [l for l in X if set(l) != {"?"}]
Out[153]: [['a', '?', '?', '?', '?', '?', '?'], ['?', 'b', '?', '?', '?', '?', '?']]

set(l) gets the unique values of the list and makes a set out of it, comparing the resulting set with {"?"} would suffice as you want to drop the list with all ?s.

like image 186
heemayl Avatar answered Jan 29 '23 10:01

heemayl