Skip to main content
 首页 » 编程设计

python之如何在 Python 中访问 OrderedDict 中的上一个键和值

2024年11月01日12zdz8207

如何在 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  

请您参考如下方法:

您可以使用 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)])