2017-01-10 39 views
0

我有一個大的嵌套循環稱爲classarray充滿關於不同類的信息。我試圖結合同一類的類,因爲前兩個嵌套循環索引中的數據是相同的。如何將新變量設置爲另一個變量的實際值而不是其內存位置?

[['AAS', '100', 'Intro Asian American Studies', '0', '12', '8', '5', '1', '3', '0', '0', '0', '0', '0', '0', '0', 'S-15'] 
['AAS', '100', 'Intro Asian American Studies', '1', '10', '4', '3', '6', '0', '1', '2', '0', '0', '0', '0', '0', 'S-15'] 
['AAS', '100', 'Intro Asian American Studies', '1', '7', '6', '7', '4', '1', '0', '1', '0', '0', '0', '0', '0', 'S-15'] 
['AAS', '120', 'Intro to Asian Am Pop Culture', '6', '7', '5', '2', '0', '3', '3', '0', '1', '0', '0', '0', '1', 'S-15'] 
['AAS', '215', 'US Citizenship Comparatively', '1', '3', '5', '4', '1', '6', '1', '3', '2', '1', '1', '1', '0', 'F-15'] 
['AAS', '258', 'Muslims in America', '0', '19', '2', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', 'S-16'] 
['AAS', '365', 'Asian American Media and Film', '1', '4', '6', '4', '5', '1', '3', '2', '2', '0', '0', '1', '0', 'S-16'] 
['AAS', '365', 'Asian American Media and Film', '6', '15', '0', '0', '1', '0', '3', '1', '1', '0', '0', '0', '2', 'S-15']] 

我已經寫了下面這段代碼嘗試行組合併產生新的數組稱爲new_array:

itemx = ['','','',0,0,0,0,0,0,0,0,0,0,0,0,0,''] 
newarray=[] 
for course,courseplus1 in zip(classarray,classarray[1:]): 
    if (course[0]==courseplus1[0] and course[1]==courseplus1[1]): 
     itemx[0]=course[0] 
     itemx[1]=course[1] 
     itemx[2]=course[2] 
     for number in range(3,16): 
      itemx[number]=itemx[number]+(int(course[number])+int(courseplus1[number])) 
     itemx[16]=course[16] 
    else: 
     newarray.append(itemx) 
     print(itemx) 
     itemx[0]=courseplus1[0] 
     itemx[1]=courseplus1[1] 
     itemx[2]=courseplus1[2] 
     for number in range(3,16): 
      itemx[number]=int(courseplus1[number]) 

for item in newarray: 
    print(item) 

但是,輸出是這樣的:

['AAS', '365', 'Asian American Media and Film', '7', '19', '6', '4', '6', '1', '6', '3', '3', '0', '0', '1', '2', 'S-16'] 

5倍。 從我的理解通過堆棧溢出看,其原因是因爲:

newarray.append(itemx) 

追加itemx到列表中; itemx是一個單獨的內存位置,最後是AAS 365的信息。所以,新數組,作爲itemx的列表,裏面有一堆itemx。

我的問題是:我該如何處理或減輕這個問題?爲了創建類庫,我做了同樣的事情,除了我在for循環中聲明瞭itemx之外,我理解的意思是itemx是具有新位置的新變量。

+0

的可能的複製[如何克隆或複製一個列表?(http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) –

+0

當您指定到循環內的'itemx',它是*相同的變量*,它獲得了循環每次迭代所分配的新引用。術語說明:Python中沒有變量聲明。 –

回答

0
>>> from copy import copy, deepcopy 
help(copy) 
help(deepcopy) 

>>> a = [1] 
>>> b = copy(a) 
>>> b.append(1) 
>>> b 
[1, 1] 
>>> a 
[1] 
+0

或者只是'list(a)' –

+0

當然。它只是'copy'和'deepcopy'兩者都適用於其他類型的對象。 – abcdn

0

在諮詢了一些有經驗的朋友之後,我能夠解決我的問題。我需要做的是在將itemx附加到newarray後,在我的else語句中「redeclare」itemX。這將它指向記憶中的新位置(我認爲)!

else: 
    newarray.append(itemx) 
    itemx = ['', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ''] 
    itemx[0]=courseplus1[0] 
    itemx[1]=courseplus1[1] 
    itemx[2]=courseplus1[2] 
    for number in range(3,16): 
     itemx[number]=int(courseplus1[number]) 
相關問題