我正在尝试在 python 中创建一个带有 xyz 坐标的 json 转储,但是我用来遍历不同组的 for 循环只返回最后一组
self.group_strings = ['CHIN', 'L_EYE_BROW', 'R_EYE_BROW', 'L_EYE', 'R_EYE', 'T_NOSE', 'B_NOSE', 'O_LIPS', 'I_LIPS']
if reply == QMessageBox.Yes:
for grp_str in self.group_strings:
coords_data = self.point_dict[grp_str]['Coords']
data = coords_data
with open("data_file.json", "w") as write_file:
json.dump(data, write_file)
预期结果是一个 JSON 文件,其放置点的坐标如下:
[[x,y,z][x,y,z][x,y,z][x,y,z][x,y,z][x,y,z] 等...]。
放置点的每个括号,当前输出是:
[[x, y, z] [x, y, z] [x, y, z] [x, y, z] [x, y, z] [x, y, z] [x, y, z] [x,y,z]]。
由于最后一组的大小为 8,因此只有 8 个值
在尝试了你的一些解决方案后,我最终得到了这个:
data = []
if reply == QMessageBox.Yes:
for grp_str in self.group_strings:
data.append(self.point_dict[grp_str]['Coords'])
with open("data_file.json", "w") as write_file:
json.dump(data, write_file)
打印(数据)的输出是:
[[17.006101346674598,-24.222496770994944,95.14869919154683],[22.30318006424494,-21.376267007401097,94.70820903177969],[-24.066693590510965,21.205230021220736,96.57992975278633],[-7.9541006992288885,20.3986457061961,103.06739548846576],[-28.291138300128495,33.5422782651503,99.22546203301508],[-40.61999270785583, 40.90496355476136,90.2356807538543],[-39.293698815625135,52.39636618754361,96.72998820004932],[-28.29463915487483,48.772250886978405,102.25119515066885]]
在for
循环中,您data
在每次迭代时都使用data = coords_data
. 如果data
是一个列表,则使用data.append(coords_data)
它在每次迭代时向其添加新数据。请注意,您需要在for
循环之前对其进行初始化data = []
本质上:
data = []
for grp_str in group_strings:
data.append(self.point_dict[grp_str]['Coords'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句