adding list value into dictionary after appending new value into list during each iteration
这是我将列表值附加到字典中的程序
| 1 2 3 4 5 6 7 8 9 10 | lis=['a','b','c'] st=['d','e'] count=0 f={} for s in st: lis.append(s) f[count]=lis count+=1 print f | 
我期望的输出是
| 1 | {0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} | 
但我得到了
| 1 | {0: ['a', 'b', 'c', 'd', 'e'], 1: ['a', 'b', 'c', 'd', 'e']} | 
作为输出。请帮我解决这个问题。事先谢谢。
在放入
| 1 | f[count]= lis[:]           # copy lis | 
你得到:
| 1 2 | {0: ['a', 'b', 'c', 'd']} {0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} | 
注:感谢@padraiccunningham指出,
您需要
| 1 2 3 4 5 6 7 8 9 10 | 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 | 
产量
| 1 2 | {0: ['a', 'b', 'c', 'd']} {0: ['a', 'b', 'c', 'd'], 1: ['a', 'b', 'c', 'd', 'e']} | 
| 1 2 3 4 | 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']} |