【问题标题】:adding list value into dictionary after appending new value into list during each iteration在每次迭代期间将新值附加到列表中后,将列表值添加到字典中
【发布时间】:2014-07-28 01:19:27
【问题描述】:

这是我将列表值附加到字典中的程序

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: ['a', 'b', 'c', 'd', 'e'], 1: ['a', 'b', 'c', 'd', ' e']}
  • a 中的f[count]=a 是什么?
  • f[count] = lis + [s]

标签: python


【解决方案1】:

你需要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']}

【讨论】:

  • 您实际上并不需要深度复制,因为列表中的元素不是对对象的引用。您只需要复制列表即可。
  • 为什么不使用f[count]=lis[:]
  • @PadraicCunningham 也可以,并且可以保存 copy 模块的导入。我想我只是想让 OP 非常清楚他们确实需要列表的副本,因为他们不希望所有键都指向与其值相同的列表。
【解决方案2】:
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']}

【讨论】:

  • 这篇文章被自动标记为低质量,因为它只是代码。你会通过添加一些文本来扩展它来解释它是如何工作的/它是如何解决问题的吗?
【解决方案3】:

在输入 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?How to clone or copy a list?)。

【讨论】:

  • 使用f[count]=lis[:] 效率更高
  • @PadraicCunningham 能给个参考吗?
  • @PadraicCunningham 谢谢,我找到了参考。不过,如果您有更好的想法,请发布另一个。
  • 对于非常小的列表,它与函数调用相关的开销使其变慢(即使调用空函数也需要一些纳秒),否则比切片略快。但是应该首选切片,因为很多时候人们使用列表作为变量名。 (Python 2)
  • @PadraicCunningham 我希望l 是你的情况不是range(100)。因为range() 的切片在 Python 3 中需要固定的时间。
猜你喜欢
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
相关资源
最近更新 更多