Python for循环只返回字典的最后一个值

2024-09-26 17:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的xyz坐标创建一个json转储,但是im用于遍历不同组的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][x,y,z][x,y,z]]。在

只有8个值,因为最后一个组的大小是8

在尝试了你的一些解决方案后,我得出了这样的结论:

^{pr2}$

打印(数据)输出为:

[[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]]


Tags: selfjsonfordatagroupcoordsnosefile
3条回答

您的with块在for循环之外,因此它在循环结束后执行,并且只能访问最后一个元素,因为这是循环终止时的状态。在

但是,如果每次在循环块内部打开一个with,则会再次得到相同的结果,因此必须使用append模式“a+”打开它

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 is now inside the for loop
       with open("data_file.json", "a+") as write_file:
           json.dump(data, write_file)

更好的方法是在上下文管理器中运行循环。在

^{pr2}$

for循环中的每次迭代之后,都要重写data变量,因此只能得到最后一次迭代。您需要初始化一些内容,以便将每次数据迭代转储到某种“结果”数据中:

self.group_strings = ['CHIN', 'L_EYE_BROW', 'R_EYE_BROW', 'L_EYE', 'R_EYE', 'T_NOSE', 'B_NOSE', 'O_LIPS', 'I_LIPS']

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)

for循环中,在每次迭代中使用data = coords_data重写{}。如果data是一个列表,那么在每次迭代时使用data.append(coords_data)向其添加新数据。请注意,您需要在使用data = []for循环之前初始化它

基本上:

data = []
for grp_str in group_strings:
   data.append(self.point_dict[grp_str]['Coords'])

相关问题 更多 >

    热门问题