首页 > 解决方案 > 如何将内部列表存储到外部列表

问题描述

#Total distance values are stored here
total_dis = []
#Permutation of cooridnates 
perm = permutations(result_List, num_dot)
for i in perm: 
    route = list(i)
    route.append(route[0])
    print(route)
    for (x1, y1), (x2, y2) in zip(route, route[1:]):
        distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        print(distance_formula)

我正在计算每个生成的排列的点之间的距离。

[(5, 0), (4, 5), (2, 9), (5, 0)]
5.0990195135927845
4.47213595499958
9.486832980505138
[(5, 0), (2, 9), (4, 5), (5, 0)]
9.486832980505138
4.47213595499958
5.0990195135927845
[(4, 5), (5, 0), (2, 9), (4, 5)]
5.0990195135927845
9.486832980505138
4.47213595499958
...

我正在尝试将列表中的值存储distance_formula在列表中total_dis。(我认为将浮点数存储在一个列表中可以让我找到每个列表的总和。)像这样:

[[5.0990195135927845, 4.47213595499958, 9.486832980505138],[9.486832980505138, 4.47213595499958, 5.0990195135927845], [5.0990195135927845, 9.486832980505138, 4.47213595499958],[...]]

我无法为要存储的每个排列的每个点之间的距离创建新列表。

标签: pythonlistcoordinatespermutationnested-loops

解决方案


只需添加三行

#Total distance values are stored here
total_dis = []
#Permutation of cooridnates 
perm = permutations(result_List, num_dot)
for i in perm: 
    route = list(i)
    route.append(route[0])
    print(route)
    dis_list = []                             # <----  Add this line 
    for (x1, y1), (x2, y2) in zip(route, route[1:]):
        distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        print(distance_formula)
        dis_list.append(distance_formula)     # <----  Add this line 
    total_dis.append(dis_list)                # <----  Add this line (outside the "distance" loop)

您甚至可以选择将其作为嵌套列表推导式来执行,尽管它的可读性可能要低得多。

total_dis = [
    [
        math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        for (x1, y1), (x2, y2) in zip(
                i + (i[0], )[:-1],
                i + (i[0], )[1:]
            )
    [
    for i in permutations(result_List, num_dot)
]

推荐阅读