我正在尝试使用以下源代码更新列表列表中的值:
target_agreement = get_object_or_404(TargetAgreement.objects, pk=agreement_id)
target_category_set = TargetCategory.objects.filter(company=target_agreement.company, is_active=True).order_by('position')
category_targets = []
if target_category_set:
totals = [[0]*3]*len(target_category_set) #list of lists with list on level 2 having length of 3
else:
totals = [[0]*3]*1
for (index1,target_category) in enumerate(target_category_set):
category_targets_temp = []
for (index2,target) in enumerate(target_category.category_targets.filter(user=request.user, agreement=target_agreement)):
category_targets_temp.append(target)
print "*******"
print "index is: "
print index1
print totals[index1][0]
totals[index1][0] = totals[index1][0] + target.weight
print totals[index1][0]
print "totals are"
print totals
print "*******"
print "final result"
print totals[index1][0]
print totals
print "-----"
category_targets.append(category_targets_temp)
print totals
我不明白的行为totals[index1][0] = totals[index1][0] + target.weight
不仅是更新 index1 引用的列表中的第一个元素,而且是所有列表中的所有第一个元素。
结果如下:
[[88, 0, 0], [88, 0, 0], [88, 0, 0], [88, 0, 0]]
但我本来预计:
[[36, 0, 0], [50, 0, 0], [1, 0, 0], [1, 0, 0]]
有人可以澄清我做错了什么。谢谢你的帮助。