Skip to main content
 首页 » 编程设计

python之从循环中的数组中删除对象

2025年02月15日9mfryf

一般来说,我有以下(当然是简化的)程序结构:

for i in range(len(EdgePixels)): 
    for j in range(len(EdgePixels)): 
        for k in range(len(EdgePixels)): 
            # Now in here I want to delete some Entries from the Array... 
            # e.g. I want to remove EdgePixels[5], so: 
            del EdgePixels[5] 

如果我尝试运行它(不完全是这 4 行,但问题出在这一行)我当然会得到错误

"List index out of range"...

问题是,我还在外部 2 个 for 循环中使用数组。

我的目标是,我可以从内部 for 循环中的数组中删除一些“不必要的”条目,并且外部 2 for 循环可以继续使用“新数组”运行删除的条目...

有没有办法解决这个问题?

请您参考如下方法:

最简单的方法是忽略索引而不是删除这些元素:

ignore_indices = set() 
 
for i, item1 in enumerate(EdgePixels): 
    if i in ignore_indices: 
        continue 
    for j, item2 in enumerate(EdgePixels): 
        if j in ignore_indices: 
            continue 
        for k, item3 in enumerate(EdgePixels): 
            ignore_indices.add(5)