Mehtab Pathan
Mehtab Pathan

Reputation: 483

Filter nested list python

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

A nested list of coordinates are as given in a.

For example (1,2) refers to x,y coordinates.

Imposing condition that x,y> 0 & <10 and deleting those points.

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

Expected result a=[[(5,6),(7,2)]] This is the error I get:

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

Upvotes: 0

Views: 2348

Answers (2)

EvenLisle
EvenLisle

Reputation: 4812

The following snippet will print [[(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

Upvotes: 1

mhawke
mhawke

Reputation: 87084

Try this list comprehesion.

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

Upvotes: 3

Related Questions