【发布时间】:2021-07-06 12:35:31
【问题描述】:
我正在尝试使用 for 循环填充字典列表,但最终结果显示由 for 循环填充的最后一个字典会覆盖所有先前字典的值。我尝试将How to populate Python dictionary using a loop 中提出的解决方案调整为我的代码,但我仍然得到相同的结果。
我过去曾将.append() 用于列表对象,但我不确定为什么每次迭代都会覆盖字典。这是我要实现的目标的可重现示例:
my_list1 = [{'x1':1, 'x2':2.4, 'x3':3}, {'x1':4.5, 'x2':5, 'x3':6}, {'x1':7.9, 'x2':8.3, 'x3':9}, {'x1':3, 'x2':0.3, 'x3':4}]
list_test = []
foo = {}
for i in range(4):
for j in range(3):
if isinstance(list(my_list1[i].values())[j], float) and list(my_list1[i].values())[j] > 0.1:
foo[list(my_list1[i].keys())[j]] = [float(x) for x in np.linspace(start = list(my_list1[i].values())[j] - 0.5, stop = list(my_list1[i].values())[j] + 0.5, num = 3)]
elif isinstance(list(my_list1[i].values())[j], int) and list(my_list1[i].values())[j] > 0.1:
foo[list(my_list1[i].keys())[j]] = [float(x) for x in np.linspace(start = list(my_list1[i].values())[j] - 0.5, stop = list(my_list1[i].values())[j] + 0.5, num = 3)]
list_test.append(foo)
运行上述代码时list_test的实际输出为:
[{'x1': [2.5, 3.0, 3.5], 'x2': [-0.2, 0.3, 0.8], 'x3': [3.5, 4.0, 4.5]},
{'x1': [2.5, 3.0, 3.5], 'x2': [-0.2, 0.3, 0.8], 'x3': [3.5, 4.0, 4.5]},
{'x1': [2.5, 3.0, 3.5], 'x2': [-0.2, 0.3, 0.8], 'x3': [3.5, 4.0, 4.5]},
{'x1': [2.5, 3.0, 3.5], 'x2': [-0.2, 0.3, 0.8], 'x3': [3.5, 4.0, 4.5]}]
但我期待看到:
[{'x1': [0.5, 1.0, 1.5], 'x2': [1.9, 2.4, 2.9], 'x3': [2.5, 3.0, 3.5]},
{'x1': [4.0, 4.5, 5.0], 'x2': [4.5, 5.0, 5.5], 'x3': [5.5, 6.0, 6.5]},
{'x1': [7.4, 7.9, 8.4], 'x2': [7.8, 8.3, 8.8], 'x3': [8.5, 9.0, 9.5]},
{'x1': [2.5, 3.0, 3.5], 'x2': [-0.2, 0.3, 0.8], 'x3': [3.5, 4.0, 4.5]}]
任何实现解决方案的建议将不胜感激。
【问题讨论】:
-
你能解释一下这个输出是如何实现的吗?解释用于将输入更改为预期输出的逻辑
标签: python list dictionary for-loop