这是我将列表值附加到字典
的程序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)
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']}
答案 1 :(得分:0)
您需要copy
列表,因为如果您将其添加到字典然后修改它,它将更改字典中存在的所有副本。
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']}
答案 2 :(得分:0)
只需在放入f
之前复制列表,以便在将元素添加到原始列表时它的值不会发生变化:
f[count]= lis[:] # copy lis
你得到:
{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?或{ {3}})。