如何在python中从另一个列表中删除索引列表?
我有两张长长的单子。我基本上想从这个列表中删除与条件不匹配的元素。比如说,如何在python中从另一个列表中删除索引列表?,python,list,Python,List,我有两张长长的单子。我基本上想从这个列表中删除与条件不匹配的元素。比如说, list_1=['a', 'b', 'c', 'd'] list_2=['1', 'e', '1', 'e'] 清单一和清单二相互对应。现在,我想从列表1中删除某些与我的条件不匹配的元素。我必须确保我从列表2中删除了相应的元素,并且顺序不会混乱 所以我创建了一个for循环,它遍历列表1并存储所有必须删除的元素的索引 比如说: index_list = ['1', '3'] 基本上,我需要确保从列表1中删除b和d,从
list_1=['a', 'b', 'c', 'd']
list_2=['1', 'e', '1', 'e']
清单一和清单二相互对应。现在,我想从列表1中删除某些与我的条件不匹配的元素。我必须确保我从列表2中删除了相应的元素,并且顺序不会混乱
所以我创建了一个for循环,它遍历列表1并存储所有必须删除的元素的索引
比如说:
index_list = ['1', '3']
基本上,我需要确保从列表1中删除b和d,从列表2中删除e和e。我该怎么做
我试过:
del (list_1 [i] for i in index_list)]
del (list_2 [i] for i in index_list)]
但我得到一个错误,索引必须是一个列表,而不是列表。我还尝试:
list_1.remove[i]
list_2.remove[i]
但这也不起作用。我尝试创建另一个循环:
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)
但这也不起作用。这给了我一个错误,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']
>>>
index_list.sort(reverse=True, key=int)
for i in index_list:
del(list_1[int(i)])
del(list_2[int(i)])
那么:
list_1, list_2 = zip(*((x, y) for x, y in zip(list_1, list_2) if f(x)))
其中f
是一个函数,用于测试列表_1
中的某个值是否与您的条件匹配
例如:
list_1 = ['a', 'b', 'c', 'd']
list_2 = ['1', 'e', '1', 'e']
def f(s):
return s == 'b' or s == 'c'
list_1, list_2 = zip(*((x, y) for x, y in zip(list_1, list_2) if f(x)))
print list_1
print list_2
(‘b’、‘c’)
('e','1')
(请注意,此方法实际上将list1
和list2
转换为元组,这对于您的用例来说可能没问题,也可能没问题。如果您确实需要将它们转换为列表,那么您可以很容易地将它们转换为列表,并使用以下行:
list_1, list_2 = list(list_1), list(list_2)
就在“主”行之后。)您可以尝试以下方法:
index_list.sort(reverse=True, key=int)
for i in index_list:
del(list_1[int(i)])
del(list_2[int(i)])
或者您也可以这样做:
list_1 = [item for item in list_1 if f(item)]
list_2 = [item for item in list_2 if f(item)]
其中
f
是一个函数,根据您的条件返回真/假。就像在您的示例中一样,这可以是,def(item):returnitem!='a'和项目!='c'和项目!='e’
晚会有点晚了,但这里有另一个版本
list_1=['a', 'b', 'c', 'd']
list_2=['1', 'e', '1', 'e']
index_list = ['1', '3']
#convert index_list to int
index_list = [ int(x) for x in index_list ]
#Delete elements as per index_list from list_1
new_list_1 = [i for i in list_1 if list_1.index(i) not in index_list]
#Delete elements as per index_list from list_2
new_list_2 = [i for i in list_2 if list_2.index(i) not in index_list]
print "new_list_1=", new_list_1
print "new_list_2=", new_list_2
输出
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
new_list_1= ['a', 'c']
new_list_2= ['1', '1']
>>>