首页 > 解决方案 > 给定循环中的起始字典键,如何在遍历字典时从字典中删除项目

问题描述

我试图从字典中的点绘制折线 {OID:PointGeometry,,,},我试图从给定的 OID 开始并找到存储在另一个字典中的最近点。第二个字典与第一个字典完全相同,只是它缺少在第一个字典中搜索的第一个点。在遍历字典时,我想删除从字典中绘制的点,这样线条就不会重叠。1 部词典有 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]

标签: pythondictionarypolylinearcpyarcmap

解决方案


我在 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]

推荐阅读