Python 我正试图根据另一个列表中的项目(在循环中)从列表中删除项目。错误:列表索引超出范围

Python 我正试图根据另一个列表中的项目(在循环中)从列表中删除项目。错误:列表索引超出范围,python,list,Python,List,这是我的代码: print('oc before remove',oc) print('remlist before remove', remlist) for i in range(len(remlist)): for j in range(len(oc)): if ( (remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1]) ): del oc[j] print('oc afte

这是我的代码:

print('oc before remove',oc)
print('remlist before remove', remlist)

for i in range(len(remlist)):
    for j in range(len(oc)):
        if ( (remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1]) ):
            del oc[j]

print('oc after remove', oc)
“oc”是要从中删除也出现在“remlist”中的项目的de列表。My
打印
输出以下内容:

('oc before remove', [[0, 0, 0]])
('remlist before remove', [[0, 0, 0]])
('oc after remove', [])
('oc before remove', [[1, 0, 1], [0, 1, 1]])
('remlist before remove', [[0, 0, 0], [1, 0, 1]])
这里发生了错误

因此,第一次成功,但第二次出现以下错误:

IndexError: list index out of range

我理解这个错误的含义,但我不明白为什么这里会发生这个错误。我使用两个列表的长度来循环。这里出了什么问题?

您的问题是在迭代过程中更改列表的大小。这显然是一个问题,因为删除一些项目后,
j
循环变量将超出新(删除后)列表长度的范围。第一次它只起作用,因为列表只包含1个元素

请尝试以下方法:

oc = [item for item in oc if item not in remlist]
此列表理解将保留
oc
中不在
remlist

len(oc)
中的项目。当您进入循环时,仅对其求值一次,但在一次迭代后,您删除了一个元素,因此列表的长度会发生变化。在下一次迭代中,您试图访问oc[1][0],但此时oc只有1个元素,因此引发异常


还请注意,您只比较每个元素中的前2个元素(在您的示例中,每个元素包含3个元素)。

问题在于,您在循环列表时从列表中删除了项目。 对于长度为1的列表,这不会产生任何问题,但如果长度大于1,则会产生问题,因为列表在循环时会变短

在您的第二个示例中,您事先告诉循环遍历2项(因为您的列表长度为2)。但是,如果您找到并删除一个项目,列表将变小,并且它将无法循环您预先设置的完整范围。我已成为长度为1的列表,因此您无法访问第二项。

有两种方法: 1) 创建新列表并在其中复制
oc
remlist
中的元素, 2) 直接从oc中删除remlist中的元素(如果oc很大)

复制到新列表中 直接从列表中删除 在这里,您可以使用remove

for e in remlist:
    for i in xrange(oc.count(e)): oc.remove(e)
评论 我不知道为什么只比较子列表的第一个和第二个元素:

if ((remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1])): ...
写下来就足够了:

if (remlist[i] == oc[j]): ...
如果您确信自己在做什么,请至少使用:

if (remlist[i][0:2] == oc[j][0:2]): ...

它更像蟒蛇;)

由于您在运行时从oc中删除了一个元素,因此它将给出
索引器:列表索引超出范围
,oc[1]元素将丢失

我使用
while loop
处理该案例

>>>oc =  [[1, 0, 1], [0, 1, 1]]
>>>remlist = [[0, 0, 0], [1, 0, 1]]
for i in range(len(remlist)):
    j = 0
    while j <len(oc):
        if ( (remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1]) ):
            del oc[j]
            j = j-1

        j = j+1

旁注:看起来您正在使用Python 2,其中
print
是一条语句。不要试图将其用作函数,您正在打印元组。
>>>oc =  [[1, 0, 1], [0, 1, 1]]
>>>remlist = [[0, 0, 0], [1, 0, 1]]
for i in range(len(remlist)):
    j = 0
    while j <len(oc):
        if ( (remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1]) ):
            del oc[j]
            j = j-1

        j = j+1
>>>oc
[[0, 1, 1]]
>>>remlist
[[0, 0, 0], [1, 0, 1]]