2013-11-15 50 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)])