2

如何在 Python 中的 OrderedDict 中访问上一个键和值?我正在尝试计算从起点到折线的每个点的距离。在 self._line 中,键是一对坐标 (x, y),值是从折线开始到线段的距离。在下面的代码中,起始位置距离为零,接下来是所有折线段的总和。没有标志 prev_x, prev_y 有没有更优雅的方法来做到这一点

    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 
4

1 回答 1

2

You can use zip to enumerate over a list pair-wise, something like this:

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

Here's an example with sample inputs:

>>> 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)])
于 2013-11-15T02:01:36.270 回答