Python:删除满足特定条件的所有列表索引

Wil*_*ill 5 python list del indices

为了解决这个问题,我试图遍历 python 中的坐标对列表,并删除其中一个坐标为负的所有情况。例如:

在数组中:

map = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]
Run Code Online (Sandbox Code Playgroud)

我想删除其中任一坐标 < 0 的所有对,留下:

map = [[2, 3], [7, 1]]
Run Code Online (Sandbox Code Playgroud)

我的问题是 python 列表不能有任何间隙,所以如果我这样循环:

i = 0
for pair in map:
        for coord in pair:
            if coord < 0:
                del map[i]
    i += 1
Run Code Online (Sandbox Code Playgroud)

当元素被删除时,所有的索引都会发生变化,扰乱迭代并导致各种问题。我尝试将坏元素的索引存储在另一个列表中,然后循环遍历并删除这些元素,但我遇到了同样的问题:一旦一个元素消失,整个列表就会发生变化,索引不再准确。

有什么我想念的吗?

谢谢。

unu*_*tbu 3

如果列表不大,那么最简单的方法是创建一个新列表:

In [7]: old_map = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]

In [8]: new_map=[[x,y] for x,y in a_map if not (x<0 or y<0)]

In [9]: new_map
Out[9]: [[2, 3], [7, 1]]
Run Code Online (Sandbox Code Playgroud)

old_map = new_map如果您想丢弃其他对,您可以跟进此操作。

如果列表太大,创建一个大小相当的新列表是一个问题,那么您可以就地从列表中删除元素——技巧是首先从尾端删除它们:

the_map = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]
for i in range(len(the_map)-1,-1,-1):
    pair=the_map[i]
    for coord in pair:
        if coord < 0:
            del the_map[i]

print(the_map)
Run Code Online (Sandbox Code Playgroud)

产量

[[2, 3], [7, 1]]
Run Code Online (Sandbox Code Playgroud)

附言。map是一个非常有用的内置 Python 函数。最好不要命名变量,map因为这会覆盖内置变量。