如何在Python中从另一个列表中删除索引列表?

10

我有两个很长的列表。基本上,我想从这些列表中删除不符合条件的元素。例如,

list_1=['a', 'b', 'c', 'd']

list_2=['1', 'e', '1', 'e']
列表一和列表二相互对应。现在我想从列表一中删除不符合我的条件的某些元素。我必须确保同时从列表二中删除相应的元素,而且顺序不会混乱。 因此,我创建了一个for循环来遍历列表一,并存储所有需要删除元素的索引。 假设:
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。我也尝试过以下方式:

但是我得到一个错误,指出indices必须是一个列表,而不是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不是全局名称。

4个回答

4

试试这个:

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

1
怎么样:
list_1, list_2 = zip(*((x, y) for x, y in zip(list_1, list_2) if f(x)))

这里的 f 是一个函数,用于测试在 list_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')

(请注意,此方法实际上会将list1list2转换为元组,这可能对您的用例有利或不利。如果您确实需要它们成为列表,则可以使用以下代码轻松地将它们转换为列表:

list_1, list_2 = list(list_1), list(list_2)

在“primary”行之后。

0
你可以尝试这个:
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是一个函数,根据您的条件返回True/False。就像在您的示例中,可以这样写:def f(item): return item != 'a' and item != 'c' and item != 'e'


0
有点晚了,但这里是另一个版本。
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']
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接