Mohamed Saleh
Mohamed Saleh

Reputation: 41

Why do I get this error while trying to remove an array of arrays from a list?

I have a list with every element is an array of arrays. Something like this:

contourList = [  [ [x0,y0],[x1,y1]...] ,[ [x2,y2],[x3,y3] ]...]

Every list element is an array of coordinates representing a contour in x-y dimensions and every coordinate is an array of length 2 representing x,y values..

Now I want to check if a given contour "array of arrays" exists in this list and if yes, then remove it. When I do this I get an error:

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

This is the code:

for contour in contourList:
    if equalCoords(contour, mycontour):
        contourList.remove(contour)

and I use this method "equalCoords to check if 2 contours are the same or not. It is:

def equalCoords(contourA,contourB):
    if len(contourA)!=len(cylinderB):
        return False
    else:
        for contourCoordA,contourCoordB in zip(contourA,contourB):
            if contourCoordA[0]!=contourCoordB[0] or contourCoordA[1]!=contourCoordB[1]:
                return False
    return True

Here is an example of a contour:

[[ 240.0696526   413.        ]
 [ 241.          412.31021016]
 [ 241.57079161  412.        ]
 [ 242.          411.77849971]
 [ 243.          411.41933059]
 [ 244.          411.21092001]
 [ 245.          411.13343726]
 [ 246.          411.1804759 ]
 [ 247.          411.35514159]
 [ 248.          411.6721164 ]
 [ 248.68715031  412.        ]
 [ 249.          412.15537894]
 [ 250.          412.82438379]
 [ 250.20954831  413.        ]]

The code works fine and successfully removes some contours but then after some iterations it stops and gives the error I mentioned above.

Please let me know if my question is not clear enough.

Upvotes: 1

Views: 957

Answers (1)

zardav
zardav

Reputation: 1248

I guess the problem is when you do remove it look for item that equal to contour, but contour is a list, and it checks inside whether list1==list2, that cause this error. So you can use pop instead, or to use list comprehensions.

You can do:

i = 0
while i < len(contourList):
  if equalCoords(contourList[i], mycontour):
    contourList.pop(i)
  else:
    i += 1

Or:

contourList = [c for c in contourList if not equalCoords(c, mycontour)]

Or:

contourList = filter(lambda c: not equalCoords(c, mycontour), contourList)

Upvotes: 1

Related Questions