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

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

本文介绍了Python for循环仅返回字典的最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中使用xyz坐标创建json转储,但是用于遍历不同组的for循环即时消息只会返回最后一个组

I'm trying to create a json dump with xyz coordinates in python, however the for loop im using to go trough different groups only returns the last group

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文件,其放置点的坐标如下:

The expected outcome is a JSON file with the coordinates of the placed points as following:

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

放置点的每个括号中,当前出现的是:

Every bracket for the placed point, the current out come is:

[[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个值

Only 8 values since the size of the last group is 8

尝试了您的某些解决方案后,我得出了以下结论:

After trying some of your solutions I've ended up with this:

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)

print(data)的输出是:

The output of print(data) is:

推荐答案

for循环中,您每次使用data = coords_data覆盖data.如果data是列表,则使用data.append(coords_data)代替,以便在每次迭代时向其中添加新数据.请注意,您需要在for循环之前使用data = []

In the for loop, you're overwriting data at every iteration with data = coords_data. If data is a list, then use data.append(coords_data) instead to add new data to it at each iteration. Note that you'll need to initialize it before the for loop with data = []

本质上:

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

这篇关于Python for循环仅返回字典的最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:37