python - 为什么在尝试从列表中删除数组的数组时会出现此错误?

标签 python arrays

我有一个列表,其中每个元素都是数组的数组。像这样的事情:

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/

相关文章:

c - 在结构体中打印任意大小的数组

c++ - 无法分配大小为 0 的常量数组

python - 将列表转换为字典

python - 如何使用 Python 正确单击 Selenium 中的元素?

python - 动态 Python 数组切片

java - 数组:个人号码 (CPR)

c - C 中的稀疏数组!如何实现呢?我可以只分配数组的一部分吗?

ios - 我怎么知道 Tab Bar Controller 索引是否以编程方式快速更改?

python - 在 python 上使用字典

python - 寻找没有形状限制的 dataframe.apply()