python - 如何将内部列表存储到外部列表
问题描述
#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],[...]]
我无法为要存储的每个排列的每个点之间的距离创建新列表。
解决方案
只需添加三行
#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)
]
推荐阅读
- libreoffice-calc - 如何在 libreOffice 中动态使用 DateValue 函数
- python - discord.ext.commands.errors.CommandInvokeError:命令引发异常:AttributeError:'str'对象没有属性'author'
- flutter - Flutter - 动画文本工具包,如何停止动画,所以它只淡入并显示文本,而不是淡入淡出和消失?
- sql - 从 SSRS 到 POWER BI 的数据集
- javascript - MUI 选择 | 更改所选值在输入中的显示方式
- kubernetes - 如何在微服务 CI/CD 管道中支持多个部署
- nativescript - NativeScript:自定义 NS clean 命令
- python - 比较两个 collections.defaultdict 并删除相似的值
- python - 为什么 sentinel-2 波段包含 25000 左右的值?
- flutter - 在颤振上检查互联网连接时出现问题