Python: Delete all list indices meeting a certain

2019-05-06 17:42发布

to get right down to it, I'm trying to iterate through a list of coordinate pairs in python and delete all cases where one of the coordinates is negative. For example:

in the array:

map = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]

I want to remove all the pairs in which either coordinate is < 0, leaving:

map = [[2, 3], [7, 1]]

My problem is that python lists cannot have any gaps, so if I loop like this:

i = 0
for pair in map:
        for coord in pair:
            if coord < 0:
                del map[i]
    i += 1

All the indices shift when the element is deleted, messing up the iteration and causing all sorts of problems. I've tried storing the indices of the bad elements in another list and then looping through and deleting those elements, but I have the same problem: once one is gone, the whole list shifts and indices are no longer accurate.

Is there something I'm missing?

Thanks.

8条回答
Deceive 欺骗
2楼-- · 2019-05-06 18:42

If the list is not large, then the easiest way is to create a new list:

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

You can follow this up with old_map = new_map if you want to discard the other pairs.

If the list is so large creating a new list of comparable size is a problem, then you can delete elements from a list in-place -- the trick is to delete them from the tail-end first:

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)

yields

[[2, 3], [7, 1]]

PS. map is such a useful built-in Python function. It is best not to name a variable map since this overrides the built-in.

查看更多
孤傲高冷的网名
3楼-- · 2019-05-06 18:45

You can use list comprehension for this:

>>> mymap = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]
>>> mymap = [m for m in mymap if m[0] > 0 and m[1] > 0]
>>> mymap
[[2, 3], [7, 1]]
查看更多
登录 后发表回答