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

2024-09-30 18:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字典中的点绘制多段线,{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]

Tags: infor字典绘制k2keysoidshape
2条回答

你甚至不需要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工作,应该这么说。Python2.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]

相关问题 更多 >