python中的简单列表删除不起作用

python中的简单列表删除不起作用,python,Python,正在尝试从元组列表中删除元组。从输出来看,它似乎可以删除。。。然而,它却给出了ValueError:list.remove(x):x不在列表中 oldPosition = 0 newPosition = 0 counter = -1 newPartition = copy.deepcopy(partitions) # Find which cluster the current point is in and where the move-to cluster is for clusters i

正在尝试从元组列表中删除元组。从输出来看,它似乎可以删除。。。然而,它却给出了ValueError:list.remove(x):x不在列表中

oldPosition = 0
newPosition = 0
counter = -1
newPartition = copy.deepcopy(partitions)
# Find which cluster the current point is in and where the move-to cluster is
for clusters in partitions:
    counter += 1
    if (inCluster(point,clusters)):
        oldPosition = counter
    if (cluster == clusters):
        newPosition = counter

# Do the removal and appending
print "Old: " + str(oldPosition) + "New: " + str(newPosition)
print "Remove From =  " + str(newPartition[oldPosition])
print "Remove = " + str(point)
newPartition[oldPosition].remove(point)
输出为

Old: 1New: 0
Remove From =  [(2.64, 3.3, 5.24), (1.64, 1.2, 3.82), (3.59, 7.5, 6.58), (1.94, 5.6, 4.25), (3.09, 6.5, 5.87), (0.54, 4.6, 2.27), (2.04, 4.5, 4.39), (-0.16, 3.8, 1.28)]
Remove = (2.64, 3.3, 5.24)
但是它说(2.64,3.3,5.24)不在名单上

编辑:完整代码

# Return whether a point is in a cluster
def inCluster(point, cluster):
    for points in cluster:
        if (point == points):
            return True

    return False                    # Default return: will only reach here if no points match

# Given a cluster, return the coordinates corresponding to its center of gravity
def centerOfGravity(cluster):
    total = (0,0,0)
    count = 0
    for points in cluster:
        total = tuple(map(operator.add, total, points))
        count += 1
    return (total[0] / count, total[1] / count, total[2] / count)

# Returns new partition after moving specified point from its old cluster to the new cluster
def moveToNewCluster(point, cluster, partitions):
    oldPosition = 0
    newPosition = 0
    counter = -1
    newPartition = copy.deepcopy(partitions)
    # Find which cluster the current point is in and where the move-to cluster is
    for clusters in partitions:
        counter += 1
        if (inCluster(point,clusters)):
            oldPosition = counter
        if (cluster == clusters):
            newPosition = counter

    # Do the removal and appending
    print "Old: " + str(oldPosition) + "New: " + str(newPosition)
    print "Remove From =  " + str(newPartition[oldPosition])
    print "Remove = " + str(point)
    newPartition[oldPosition].remove(point)
    newPartition[newPosition].append(point)

    # Clean up the new partition (we created at most one empty partition)
    newPartition.remove([])

    return newPartition

# Return a list of centers of gravity given the new partitions
def allCentersOfGravity(partitions):
    partitionsCoG = []
    for clusters in partitions:
        partitionsCoG.append(centerOfGravity(clusters))
    return partitionsCoG

# Find the euclidean distance in 3 space between two points
def distance(a, b):
    return math.sqrt(pow(a[0]-b[0], 2) + pow(a[1]-b[1], 2) + pow(a[2]-b[2], 2))

# Find the smallest absolute value distance from a point to a center of gravity
def minCenterDistance(point, centerOfGravities):
    minimumDistance = 10000000000
    dist = 0
    for center in centerOfGravities:
        dist = abs(distance(point, center))
        if (dist < minimumDistance):
            minimumDistance = dist
    return minimumDistance

# Given a set of points and partitions of those points, calculate the suqard error distortion
def squaredErrorDistortion(points, centerOfGravities):
    total = 0
    for point in points:
        total += pow(minCenterDistance(point, centerOfGravities), 2)
    total = total / len(points)
    return total

# Calculate the cost of moving point into cluster
# Value of a move is calculated as the old squared error distortion minus the new squared eror distortion
def moveValue(point, cluster, partitions, points):
    # Create the new partition formed by the swap
    newPartition = moveToNewCluster(point, cluster, partitions)
    # Get the centers of gravity for the clusters
    oldCoG = allCentersOfGravity(partitions)
    newCoG = allCentersOfGravity(newPartition)

    oldError = squaredErrorDistortion(points, oldCoG)
    newError = squaredErrorDistortion(points, newCoG)

    print "Old Partition: " + str(partitions)
    print "Old CoG: " + str(oldCoG)
    print "Old Error: " + str(oldError)
    print "New Partition: " + str(newPartition)
    print "New CoG: " + str(newCoG)
    print "New Error: " + str(newError)

    # Define the value as old - new.  If expecting the other way around results could be different
    moveErrorValue = oldError - newError

    return moveErrorValue


if __name__ == "__main__":
    # The points
    points = [(0.39, 3.3, 2.06), (0.09, 4.5, 1.63), (2.64, 3.3, 5.24), (1.64, 1.2, 3.82), (3.59, 7.5, 6.58),
              (1.94, 5.6, 4.25), (3.09, 6.5, 5.87), (0.54, 4.6, 2.27), (2.04, 4.5, 4.39), (-0.16, 3.8, 1.28)]

    # Initial Partition
    partitions = [[points[0], points[1]],
                  [points[2], points[3], points[4], points[5], points[6], points[7], points[8], points[9]]]
    '''
    # Center of Gravity test
    print centerOfGravity(partitions[0])

    # InCluster test
    print inCluster(points[0], partitions[1])
    print inCluster(points[0], partitions[0])
    '''
    # moveValue(points[2], partitions[0], partitions, points

    bestPartition = []
    tempPartition = copy.deepcopy(partitions)
    while (1==1):
        bestChangeValue = 0                                                                        # The higher the change value the better since we are doing old-new
        for cluster in tempPartition:
            for point in points:
                valueOfMove = moveValue(point, cluster, tempPartition, points)                 # Have to send partition over in order to find the cluster the point is currently in
                if (valueOfMove > bestChangeValue):
                    bestChangevalue = valueOfMove
                    bestPartition = moveToNewCluster(point, cluster, tempPartition)            # Create the new partition
        if (bestChangeValue > 0):
            tempPartition = bestPartition
        else:
            break
    # At the end, tempPartition holds the best k-means partition
    print "Best partition is: " + str(tempPartition)
    print "Error Value: " + str(squaredErrorDistortion(points, allCentersOfGravity(tempPartition)))
#返回点是否在群集中
def inCluster(点、群集):
对于群集中的点:
如果(点==点):
返回真值
return False#默认返回:只有在没有匹配点的情况下才会到达此处
#给定一个簇,返回其重心对应的坐标
def重心(群集):
总计=(0,0,0)
计数=0
对于群集中的点:
total=元组(map(operator.add,total,points))
计数+=1
返回(总计[0]/count,总计[1]/count,总计[2]/count)
#将指定点从旧群集移动到新群集后返回新分区
def moveToNewCluster(点、群集、分区):
oldPosition=0
newPosition=0
计数器=-1
newPartition=copy.deepcopy(分区)
#查找当前点所在的群集以及移动到群集的位置
对于分区中的群集:
计数器+=1
如果(包括(点、簇)):
oldPosition=计数器
如果(群集==群集):
newPosition=计数器
#进行移除和附加操作
打印“旧:”+str(旧位置)+“新:”+str(新位置)
打印“Remove From=“+str(newPartition[oldPosition]”)
打印“删除=”+str(点)
新建分区[oldPosition]。删除(点)
newPartition[newPosition]。追加(点)
#清理新分区(我们最多创建一个空分区)
newPartition.remove([])
返回新分区
#返回给定新分区的重心列表
def所有重心(分区):
分区scog=[]
对于分区中的群集:
分区图标追加(重心(簇))
返回分区
#在3个空间中求两点之间的欧几里德距离
def距离(a、b):
返回数学sqrt(pow(a[0]-b[0],2)+pow(a[1]-b[1],2)+pow(a[2]-b[2],2))
#找到从一点到重心的最小绝对值距离
def最小中心距离(点、重心):
最小距离=1000000000
距离=0
对于重心中的中心:
距离=绝对值(距离(点、中心))
如果(距离<最小距离):
最小距离=距离
返回最小距离
#给定一组点和这些点的分区,计算suqard误差失真
def平方误差畸变(点、重心):
总数=0
对于点到点:
总+=功率(最小中心距离(点、重心),2)
总计=总计/长度(点数)
返回总数
#计算将点移动到群集中的成本
#移动值计算为旧的平方误差失真减去新的平方误差失真
def moveValue(点、群集、分区、点):
#创建交换所形成的新分区
newPartition=moveToNewCluster(点、群集、分区)
#获取簇的重心
oldCoG=所有重心(分区)
newCoG=所有重心(新分区)
oldError=SquaredError畸变(点,oldCoG)
新误差=平方误差畸变(点,新中心距)
打印“旧分区:”+str(分区)
打印“旧齿轮:”+str(旧齿轮)
打印“旧错误:”+str(旧错误)
打印“新分区:”+str(新分区)
打印“新CoG:+str(新CoG)
打印“新错误:”+str(新错误)
#将该值定义为“旧-新”。如果你期望另一种方式,结果可能会有所不同
moveErrorValue=oldError-newError
返回moveErrorValue
如果名称=“\uuuuu main\uuuuuuuu”:
#要点
得分=[(0.39,3.3,2.06),(0.09,4.5,1.63),(2.64,3.3,5.24),(1.64,1.2,3.82),(3.59,7.5,6.58),
(1.94, 5.6, 4.25), (3.09, 6.5, 5.87), (0.54, 4.6, 2.27), (2.04, 4.5, 4.39), (-0.16, 3.8, 1.28)]
#初始分割
分区=[[点[0],点[1]],
[点[2],点[3],点[4],点[5],点[6],点[7],点[8],点[9]]
'''
#重心测试
打印重心(分区[0])
#包容性试验
打印inCluster(点[0],分区[1])
打印inCluster(点[0],分区[0])
'''
#移动值(点[2],分区[0],分区,点
最佳分区=[]
tempPartition=copy.deepcopy(分区)
而(1==1):
bestChangeValue=0#更改值越高越好,因为我们正在进行新旧转换
对于临时分区中的群集:
对于点到点:
valueOfMove=moveValue(点、簇、tempPartition、点)#必须发送分区才能找到点当前所在的簇
如果(移动值>最佳更改值):
bestChangevalue=移动值
bestPartition=moveToNewCluster(点、簇、临时分区)#创建新分区
如果(bestChangeValue>0):
tempPartition=bestPartition
其他:
打破
#最后,tempPartition拥有最好的k-means分区
打印“最佳分区为:”+str(临时分区)
打印“误差值:”+str(平方误差畸变(点、所有重心(tempPartition)))

实际问题在这一行

# Clean up the new partition (we created at most one empty partition)
newPartition.remove([])
newPartition
中没有空列表。如果您确实想确保它们不存在,可以这样做

if [] in newPartition: newPartition.remove([])

通过此更改,您的程序运行时不会出现任何问题。

什么是点?请注意,浮点数字可能存在精度问题,即您认为
等于列表中的元素,但