This question already has an answer here:
这个问题在这里已有答案:
- List of lists changes reflected across sublists unexpectedly 13 answers
- 列表更改反映在子列表中的意外13个答案
- Python initializing a list of lists [duplicate] 1 answer
- Python初始化列表列表[重复] 1个答案
I have a list that needs to contain a variable number of independent sets. When I run the following piece of code, I want to add the string "testing" to only the first set.
我有一个列表,需要包含可变数量的独立集。当我运行以下代码时,我想将字符串“testing”添加到第一组。
numberOfSets = 3
test = [set()]*numberOfSets
test[0].add("testing")
print test
However, when I print test
, it shows three identical sets that all contain testing. How can I set up my list so I can separately access each set?
但是,当我打印测试时,它会显示三个完全包含测试的相同集合。如何设置列表以便我可以单独访问每个设置?
2 个解决方案
#1
4
When you do [set()]*3
, you create three sets that reference the same object, thus when you change one value, the others change. Use a list comprehension here instead:
当您执行[set()] * 3时,您将创建三个引用同一对象的集合,因此当您更改一个值时,其他值会更改。改为使用列表推导:
>>> numberOfSets = 3
>>> test = [set() for _ in xrange(numberOfSets)]
>>> test[0].add("testing")
>>> print test
[set(['testing']), set([]), set([])]
#2
4
You can do
你可以做
test = [set() for _ in xrange(numberOfSets)] # use 'range' in Python 3.x
[set()]*x
creates a list with x
of the same set instance, whereas the comprehension above creates a new, independent set on each iteration, as desired.
[set()] * x创建一个包含相同set实例的x的列表,而上面的解释根据需要在每次迭代时创建一个新的独立集合。
In general, you should be very cautious whenever you multiply lists whose elements are mutable.
通常,每当您将元素可变的列表相乘时,您应该非常谨慎。
#1
4
When you do [set()]*3
, you create three sets that reference the same object, thus when you change one value, the others change. Use a list comprehension here instead:
当您执行[set()] * 3时,您将创建三个引用同一对象的集合,因此当您更改一个值时,其他值会更改。改为使用列表推导:
>>> numberOfSets = 3
>>> test = [set() for _ in xrange(numberOfSets)]
>>> test[0].add("testing")
>>> print test
[set(['testing']), set([]), set([])]
#2
4
You can do
你可以做
test = [set() for _ in xrange(numberOfSets)] # use 'range' in Python 3.x
[set()]*x
creates a list with x
of the same set instance, whereas the comprehension above creates a new, independent set on each iteration, as desired.
[set()] * x创建一个包含相同set实例的x的列表,而上面的解释根据需要在每次迭代时创建一个新的独立集合。
In general, you should be very cautious whenever you multiply lists whose elements are mutable.
通常,每当您将元素可变的列表相乘时,您应该非常谨慎。