我有两个长名单.我基本上想从这个列表中删除与condtion不匹配的元素.例如,
list_1=['a', 'b', 'c', 'd']
list_2=['1', 'e', '1', 'e']
Run Code Online (Sandbox Code Playgroud)
列表一和二对应.现在我想删除列表中与我的条件不匹配的某些元素.我必须确保从列表2中删除相应的元素,并且顺序不会搞砸.
所以我创建了一个遍历列表1的for循环,并存储了必须删除的元素的所有索引.
让我们说:
index_list = ['1', '3']
Run Code Online (Sandbox Code Playgroud)
基本上,我需要确保从列表1中删除b和d以及从列表2中删除e和e.我该怎么做?
我试过了:
del (list_1 [i] for i in index_list)]
del (list_2 [i] for i in index_list)]
Run Code Online (Sandbox Code Playgroud)
但我得到一个错误,索引必须是一个列表,而不是列表.我也尝试过:
list_1.remove[i]
list_2.remove[i]
Run Code Online (Sandbox Code Playgroud)
但这也不起作用.我尝试创建另一个循环:
for e, in (list_1):
for i, in (index_list):
if e == i:
del list_1(i)
for j, in (list_2):
for i, in (index_list):
if j == i:
del list_2(i)
Run Code Online (Sandbox Code Playgroud)
但这也不起作用.它给了我一个错误,即e和j不是全局名称.
尝试这个:
>>> list_1=['a', 'b', 'c', 'd']
>>> list_2 = ['1', 'e', '1', 'e']
>>> index_list = ['1', '3']
>>> index_list = [int(i) for i in index_list] # convert str to int for index
>>> list_1 = [i for n, i in enumerate(list_1) if n not in index_list]
>>> list_2 = [i for n, i in enumerate(list_2) if n not in index_list]
>>> list_1
['a', 'c']
>>> list_2
['1', '1']
>>>
Run Code Online (Sandbox Code Playgroud)