Skip to main content
 首页 » 编程设计

python之如何将 'yield' 生成器结果存储在 Python 2.7 的列表中

2025年05月04日14thcjp

我有这样的代码:

import math     
nList = [[[0, 0, 0], [3, 2, 1]],\ 
     [[]],\ 
     [[1, 1, 12]],\ 
     [[0, 0, 0], [30000, 40, 3010], [32000, 40500, 7520], [0, 0, 10520]],\ 
     [[15340, 0, 0], [104300, 0, 3630], [434000, 4434000, 63460]]] 
 
def calculate_length(x1, y1, x2, y2): 
    return math.sqrt((x1-x2)**2 + (y1 - y2)**2) 
 
def calculate_time (t1,t2): 
    return abs(t1-t2) 
 
def lengths(trace): 
    previous_x, previous_y = 0, 0 
    for index, point in enumerate(trace): 
        if point: 
            x, y, t = point 
            if index > 0: 
                yield calculate_length(x, y, previous_x, previous_y) 
            previous_x, previous_y = x, y 

如何将 calculate_length(x, y, previous_x, previous_y) 的 yield 结果存储在列表中?

nList 中有 traces,每个 trace 都有 points 和 3 个元素,[x ,y,t]。我需要存储每条迹线的长度,以便生成的输出为:

all_lengths_list=[[3]],[[]],[[]],[[30000.02667],[40509.40138],[51616.37337]],[[88960],[4446240]]] 

请您参考如下方法:

只需使用list:

result = list(lengths(trace))