附加价值,在字典中一个列表附加价值,在字典中的所有表 [英] Append value to one list in dictionary appends value to all lists in dictionary

查看:160
本文介绍了附加价值,在字典中一个列表附加价值,在字典中的所有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我在下面的方式建立空列表的字典作为值。

I am creating a dictionary with empty lists as values in the following way.

>>> words = dict.fromkeys(['coach', 'we', 'be'], [])

这本字典是这样的。

The dictionary looks like this.

>>> words
{'coach': [], 'be': [], 'we': []}

当我一个值追加到一个列表,该值被附加到所有的人都在这个例子中。

When I append a value to one list, the value is appended to all of them as in this example.

>>> words['coach'].append('test')
{'coach': ['test'], 'be': ['test'], 'we': ['test']}

问题

我的问题有两个部分。首先,为什么会出现这种情况?其次,我该怎么办呢?也就是说,我怎么能值追加到只有一个列表?

My question has two parts. First, why is this happening? Second, what can I do about it? That is, how can I append a value to only one list?

我想,在创建字典,我做了所有列表指向同一个对象。但我不明白怎么能因为当我输入 0 而不是 [] 在创建字典,然后增加值,而不是追加他们的价值观不同的表现,如果他们指向不同的对象。

I imagine that in creating the dictionary, I made all lists point to the same object. But I don't understand how that can be because when I input 0 instead of [] in dictionary creation and then add values instead of append them, the values behave differently as if they point to distinct objects.

我想AP preciate任何输入。谢谢你在前进!

I would appreciate any input. Thank you in advance!

推荐答案

dict.fromkeys 使用的同一个对象的所有值,在此情况下,可变列表...这意味着,所有的键分享的相同空列表的......当你尝试 .append 来一个列表的价值,这些更改将就地对该对象进行的,所以改变它是由所有引用可见。

dict.fromkeys uses the same object for all values, in this case a mutable list... That means, all keys share the same empty list... When you try to .append to the value of one list, the changes are made in-place to the object, so changes to it are visible by all that reference it.

相反,如果你使用的字典-COMP,例如: {K:[]对于k在['可能','我们','是']} [] 不同的空列表的,因此将是预期每个键值和工作独一无二的。

If instead you used a dict-comp, eg: {k:[] for k in ['could', 'we', 'be']} each [] is a different empty list and so would be unique for each key value and work as expected.

在关于使用 dict.fromkeys(['一','B','C'],0) 0 不可改变的目的因而是不受该疑难杂症的改变它产生新的对象,而不是改变到基础对象,不同的名称(在此情况下 - 该值不同的键)可以共享。

In regards to using dict.fromkeys(['a', 'b', 'c'], 0) the 0 is an immutable object thus isn't subject to that gotcha as changes to it result in new objects, not a change to the underlying object which different names (in this case - the values of the different keys) may share.

这篇关于附加价值,在字典中一个列表附加价值,在字典中的所有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆