2014-06-06 41 views
3

追加新值列表後,這是我的程序列表值添加到字典添加列表值到字典中每次迭代

lis=['a','b','c'] 
st=['d','e'] 
count=0 

f={} 
for s in st: 
    lis.append(s) 
    f[count]=lis 
    count+=1 
    print f 

我的預期輸出是

{0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} 

,但我得到

{0: ['a', 'b', 'c', 'd', 'e'], 1: ['a', 'b', 'c', 'd', 'e']} 

作爲輸出。請幫我解決這個問題。提前致謝。

+0

有沒有任何模式..得到結果 –

+0

沒有我需要這樣的輸出{0:['a','b','c','d','e'],1:['a ','b','c','d','e']} – user3715935

+0

f [count] = a'中的'a'是什麼? – bcorso

回答

0

您需要copy名單,因爲如果你把它添加到字典中,然後修改它,它會改變存在於詞典中的所有副本。

f[count]= lis[:]   # copy lis 

,你會得到:

import copy 
l = ['a','b','c'] 
st = ['d','e'] 
count = 0 
f = {} 
for s in st: 
    l.append(s) 
    f[count] = copy.copy(l) 
    count += 1 
    print f 

輸出

{0: ['a', 'b', 'c', 'd']} 
{0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} 
+0

您並不需要深度複製,因爲列表的元素不是對象的引用。你只需要複製列表。 – bcorso

+0

@bcorso你是對的。 – CoryKramer

+1

爲什麼不使用'f [count] = lis [:]' –

0
lis=['a','b','c'] 
st=['d','e']  
{ i :lis+st[:i+1] for i in range(0,2) } 
#output ={0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} 
+0

這篇文章被自動標記爲低質量,因爲它只是代碼。你會通過添加一些文字來解釋它如何工作/它如何解決問題來擴展它? – gung

0

只是把在f以便它爲你添加元素到原始列表值不會改變之前的列表複製:

{0: ['a', 'b', 'c', 'd']} 
{0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} 

注意:感謝@PadraicCunningham指出,[:]符號比list()快 - 至少對於小列表(請參閱What is the best way to copy a list?How to clone or copy a list?)。

+0

使用'f [count] = lis [:]'是更有效率 –

+0

@PadraicCunningham你能給一個參考嗎? – bcorso

+0

@PadraicCunningham謝謝,我找到了一個參考。不過,如果你有一個更好的想法,請張貼另一個。 – bcorso