我有一个列表,其中每个元素都是数组的数组。像这样的事情:
contourList = [ [ [x0,y0],[x1,y1]...] ,[ [x2,y2],[x3,y3] ]...]
每个列表元素都是一个坐标数组,表示 x-y 维度的轮廓,每个坐标都是一个长度为 2 的数组,表示 x,y 值。
现在我想检查此列表中是否存在给定轮廓“数组数组”,如果存在,则将其删除。当我这样做时,我收到错误:
contourList.remove(contour)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是代码:
for contour in contourList:
if equalCoords(contour, mycontour):
contourList.remove(contour)
我使用“equalCoords”这个方法来检查两个轮廓是否相同。它是:
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
这是轮廓的示例:
[[ 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. ]]
代码工作正常并成功删除了一些轮廓,但经过一些迭代后它停止并给出了我上面提到的错误。
如果我的问题不够清楚,请告诉我。
最佳答案
我猜问题是当你remove
时它会查找等于contour
的项目,但是contour
是一个列表,并且它检查内部是否list1==list2
,这会导致此错误。因此您可以使用 pop
来代替,或者使用列表推导式。
你可以这样做:
i = 0
while i < len(contourList):
if equalCoords(contourList[i], mycontour):
contourList.pop(i)
else:
i += 1
或者:
contourList = [c for c in contourList if not equalCoords(c, mycontour)]
或者:
contourList = filter(lambda c: not equalCoords(c, mycontour), contourList)
关于python - 为什么在尝试从列表中删除数组的数组时会出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416015/