Remove list items from a list of list in python

I have a list of characters:

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

and 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 the corresponding index iin List_List.

The output should be as follows:

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

I'm trying to:

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 code above, each character is removed from all lists.

How to remove Char_list[i]only from the corresponding list in List_List?

+4
source share
3 answers

Instead of using explicit indexes on zipyour two lists together, then apply 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']]
+6
source

enumerate :

>>> char_list = ['C', 'A', 'G']
>>> nested_list = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]

>>> [[j for j in i if j!=char_list[n]] for n, i in enumerate(nested_list)]
[['A', 'T'], ['C', 'T', 'G'], ['A', 'C']]

PEP 8 - . .

+4
Char_list = ['C', 'A', 'G']
List_List = [['A', 'C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
for i in range(len(Char_list)):
    List_List[i].remove(Char_list[i])
print(List_List)    

OUTPUT

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

If characters are repeated in nested lists, use

Char_list = ['C', 'A', 'G']
List_List = [['A', 'C','C','C', 'T'], ['C', 'A', 'T', 'G'], ['A', 'C', 'G']]
for i in range(len(Char_list)):
    for j in range(List_List[i].count(Char_list[i])):
        List_List[i].remove(Char_list[i])
print(List_List)
0
source

Source: https://habr.com/ru/post/1674926/


All Articles