[英]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
. 我想删除每个
Char_list[i]
从对应索引的列表i
在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
? 如何删除
Char_list[i]
只有在相应的列表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. 不要使用显式索引,而是将两个列表
zip
在一起,然后应用列表推导来过滤掉每个位置的不需要的字符。
>>> 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: 您可以将嵌套列表推导表达式的
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']]
I also suggest you to take a look at PEP 8 - Naming Conventions . 我还建议你看看PEP 8 - 命名约定 。 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 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.