如何将内部列表存储到外部列表

问题描述 投票:0回答:1
#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],[...]]

我在为要存储的每个排列的每个点之间的距离创建新列表时遇到麻烦。

python list coordinates permutation nested-loops
1个回答
0
投票

只需添加三行

#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)
© www.soinside.com 2019 - 2024. All rights reserved.