Как я могу удалить элементы из словаря при повторении словаря с учетом начального ключа словаря в цикле

Я пытаюсь нарисовать ломаные линии из точек, которые у меня есть в словаре как {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]

person Gary Lester    schedule 27.07.2018    source источник


Ответы (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
person jdehesa    schedule 27.07.2018

Я работаю в arcmap, должен был сказать это. python 2.7 не поддерживает инф. Я применил ваш ответ к доступной функции, и она работает.

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]
person Gary Lester    schedule 27.07.2018