过滤嵌套列表蟒蛇


a=[[(1,2),(7,-5),(7,4)],[(5,6),(7,2)],[(8,2),(20,7),(1,4)]]

坐标的嵌套列表如 a 所示。

例如,(1,2)是指x,y坐标。

强加x,y> 0 & <10条件并删除这些点。

for x in a:
    for y in x:
        for point in y:
            if point<=0 or point>=10:
                a.remove(x)

预期成果a=[[(5,6),(7,2)]]这是我得到的错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

试试这个列表理解。

>>> a = [[(1,2),(7,-5),(7,4)], [(5,6),(7,2)], [(8,2),(20,7),(1,4)]]
>>> [l for l in a if all((0<x<10 and 0<y<10) for x,y in l)]
[[(5, 6), (7, 2)]]

以下代码片段将打印[[(5, 6), (7, 2)]]

a=[[(1,2),(7,-5),(7,4)],[(5,6),(7,2)],[(8,2),(20,7),(1,4)]]
def f(sub):
  return all(map(lambda (x,y): (0 < x < 10 and 0 < y < 10), sub))
a = filter(f, a)
print a

最新更新