为什么对象占据列表中的最后一个值
ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; row_data = {} ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data['background-color'] = ddd[metric_id]
row_list.append(row_data)
master_list.append(row_list)
print(master_list)
输出来了:
[[{'background-color': 'green'}, {'background-color': 2}, {'background-color': 2}]]
预期产出:
[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]
答案 0 :(得分:0)
只需在内循环中移动row_data。
ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data = {}
row_data['background-color'] = ddd[metric_id]
row_list.append(row_data)
master_list.append(row_list)
print(master_list)
您将获得预期的输出:
[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]