Python:删除满足特定条件的所有列表索引 [英] Python: Delete all list indices meeting a certain condition

查看:551
本文介绍了Python:删除满足特定条件的所有列表索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要深入研究它,我试图遍历python中的坐标对列表,并删除其中一个坐标为负数的所有情况.例如:

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:

在数组中:

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

我要删除所有两个坐标都为<的对. 0,离开:

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

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

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

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.

有什么我想念的吗?

谢谢.

推荐答案

如果列表不大,则最简单的方法是创建新列表:

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

如果要丢弃其他对,可以使用old_map = new_map进行后续操作.

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)

收益

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

PS. 地图是一种有用的内置Python函数.最好不要命名变量map,因为它会覆盖内置变量.

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.

这篇关于Python:删除满足特定条件的所有列表索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆