2012-07-04 30 views
0

我想利用以下的源代碼列表的列表更新值列表更新值:Python的Django的+ - 在列表

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

有人可以澄清我做錯了什麼。謝謝你的幫助。

回答

2

原因是您創建totals列表的方式。乘以列表 -

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

您創建一個列表,其元素是對同一列表的引用。因此,當你修改一個元素時,所有元素都被修改。試想一下:

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

但是你可以通過改變列表定義避免這種情況:

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

媽呀....謝謝! :) –