0

我正在尝试使用以下源代码更新列表列表中的值:

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

有人可以澄清我做错了什么。谢谢你的帮助。

4

1 回答 1

2

The reason is the way you created that totals list. By multiplying the list -

totals = [[0]*3]*len(target_category_set) 

You create a list whose elements are references to the same list. Thus, when you modify one element, all of them are modified. Consider:

In [1]: l = [[1, 2]]*3

In [2]: l
Out[2]: [[1, 2], [1, 2], [1, 2]]

In [3]: l[0].append(3)

In [4]: l
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

But you could avoid this by changing the list definition:

In [5]: l = [[1, 2] for _ in range(3)]

In [6]: l[0].append(3)

In [7]: l
Out[7]: [[1, 2, 3], [1, 2], [1, 2]]
于 2012-07-04T08:58:27.397 回答