如何在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
答案 0 :(得分: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)])