在给定循环中的起始字典键的情况下,如何在遍历字典时从字典中删除项目

How can I remove items from a dictionary while iterating throught the dicionary given a starting dictionary key in the loop

我正在尝试从我在字典中作为 {OID:PointGeometry,} 的点绘制折线,我正在尝试从给定的 OID 开始并找到存储在另一个字典中的最近点。第二个字典与第一个字典完全相同,只是缺少第一个字典中搜索的第一个点。在遍历 dict 时,我想删除从字典中绘制的点,这样线条就不会重叠。一本词典有 141 个项目,其他 140 个项目。由于某种原因,没有点被删除,循环似乎只迭代一次。

for k in pointDict.keys():
    if k==startOid:
        distances={}
        shape=pointDict[k]
        X=shape.centroid.X
        Y=shape.centroid.Y
        Z=shape.centroid.Z
        for k2 in pointDict2.keys():
            shape2=pointDict2[k2]
            X2=shape2.centroid.X
            Y2=shape2.centroid.Y
            Z2=shape2.centroid.Z
            dist=sqrt((X-X2)**2+(Y-Y2)**2)
            distances[k2]=round(dist,4)

        minSearch=(min(distances.items(), key=lambda x:x[1]))
        print minSearch,minSearch[0]
        global startOid
        startOid=minSearch[0]
        del pointDict[k]
        del pointDict2[k2]

您甚至不需要 pointDict2。您可以执行以下操作:

import math

startOid = ...
# While there are more elements to draw
while len(pointDict) > 1:
    shape = pointDict.pop(startOid)
    X = shape.centroid.X
    Y = shape.centroid.Y
    Z = shape.centroid.Z
    nextOid = None
    minSquaredDist = math.inf
    for otherOid, otherShape in pointDict.items():
        otherX = otherShape.centroid.X
        otherY = otherShape.centroid.Y
        otherX = otherShape.centroid.Z
        squaredDist = (X - otherX) ** 2 + (Y - otherY) ** 2  + (Z - otherZ) ** 2
        if squaredDist < minSquaredDist:
            minSquaredDist = squaredDist
            nextOid = otherOid
    minDist = math.sqrt(minSquaredDist)
    print minDist, nextOid
    startOid = nextOid

我在 arcmap 工作,应该这么说。 python 2.7 不支持 inf。我将你的答案应用到可用函数中,它起作用了。

while len(pointDict) > 1:
    shape = pointDict[startOid]
    pointDict.pop(startOid)
    X = shape.centroid.X
    Y = shape.centroid.Y
    Z = shape.centroid.Z
    nextOid = None
    distances={}
    #minSquaredDist = math.inf
    for otherOid, otherShape in pointDict.items():
        X2 = otherShape.centroid.X
        Y2 = otherShape.centroid.Y
        Z2 = otherShape.centroid.Z
        squaredDist = sqrt((X-X2)**2+(Y-Y2)**2)
        distances[otherOid]=squaredDist

    minSearch=(min(distances.items(), key=lambda x:x[1]))
    print minSearch, minSearch[0]
    startOid = minSearch[0]