简体   繁体   中英

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 ?

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']]

You may use enumerate with nested list comprehension expression as:

>>> 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']]

I also suggest you to take a look at PEP 8 - Naming Conventions . You should not be using capitalized first alphabet with the variable name.

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 the characters repeat in nested lists, Use this

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)

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