Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove list items from list of list in python

I have a list of characters:

Char_list = ['C', 'A', 'G']

and a list of lists:

List_List = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]

I would like to remove each Char_list[i] from the list of corresponding index i in List_List.

Output must be as follows:

[['A','T'], ['C', 'T', 'G'], ['A', 'C']] 

what I am trying is:

for i in range(len(Char_list)):
    for j in range(len(List_List)):
        if Char_list[i] in List_List[j]:
            List_List[j].remove(Char_list[i])
print list_list

But from the above code each character is removed from all lists.

How can I remove Char_list[i] only from corresponding list in List_list?

like image 859
say.ff Avatar asked Dec 23 '22 18:12

say.ff


1 Answers

Instead of using explicit indices, zip your two lists together, then apply a list comprehension to filter out the unwanted character for each position.

>>> char_list = ['C', 'A', 'G']
>>> list_list = [['A', 'C', 'T'], ['C','A', 'T', 'G'], ['A', 'C', 'G']]
>>> [[x for x in l if x != y] for l, y in zip(list_list, char_list)]
[['A', 'T'], ['C', 'T', 'G'], ['A', 'C']]
like image 170
timgeb Avatar answered Jan 05 '23 15:01

timgeb