2013-11-15 95 views
2

如何訪問Python中OrderedDict的上一個鍵和值?我正試圖通過折線計算從起點到每點的距離。 self._line鍵是座標對(x,y),值是從段開始的多段線的距離。 在代碼中對於起始位置距離是零,對於下一個是所有多段線段的總和。 是否有更優雅的方式來做到這一點沒有標誌prev_x,prev_y如何訪問Python中的OrderedDict以前的鍵和值?

self._line = OrderedDict() 
    prev_x, prev_y = None, None 
    for x, y in passed_line: 
     self._line[(x, y)] = 0 if prev_x is None and prev_y is None else self._line[(prev_x, prev_y)] + math.sqrt((x - prev_x) * (x - prev_x) + (y - prev_y) * (y - prev_y)) 
     prev_x, prev_y = x, y 
+2

你可以通過使用一些小代數來清理它。請記住'NxN = N^2'。因此,您可以將'(x-prev_x)*(x-prev_x)+(y-prev_y)*(y-prev_y)'改變爲(x-prev_x)** 2 +(y - prev_y)** 2' 。 – iCodez

回答

2

您可以使用zip來枚舉列表成對,這樣的事情:

distance = OrderedDict() 
distance[line[0]] = 0 
for (x1, y1), (x2, y2) in zip(line, line[1:]): 
    d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 
    distance[(x2, y2)] = distance[(x1, y1)] + d 

下面是用樣本的例子輸入:

>>> from collections import OrderedDict 
>>> 
>>> line = [(1, 2), (3, 4), (0, 5), (6, 7)] 
>>> 
>>> distance = OrderedDict() 
>>> distance[line[0]] = 0 
>>> for (x1, y1), (x2, y2) in zip(line, line[1:]): 
...  d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 
...  distance[(x2, y2)] = distance[(x1, y1)] + d 
... 
>>> distance 
OrderedDict([((1, 2), 0), ((3, 4), 2.8284271247461903), ((0, 5), 5.99070478491457), ((6, 7), 12.31526010525133)])