简体   繁体   English

向集合列表中的元素添加值

[英]Add a value to an element in a list of sets

I'm using python, and I have a list of sets, constructed like this: 我正在使用python,我有一组列表,如下所示:

list = [set([])]*n

...where n is the number of sets I want in the list. ...其中n是我想要的列表中的集合数。 I want to add a value to a specific set in the list. 我想向列表中的特定集合添加一个值。 Say, the second set. 说,第二盘。 I tried 我试过了

list[1].add(value)

But this instead adds the value to each set in the list. 但这会将值添加到列表中的每个集合。 This behaviour is pretty non-intuitive to me. 这种行为对我来说很不直观。 Through further tests, I think I've found the problem: the list apparently contains 10 instances of the same set, or ten pointers to the same set, or something. 通过进一步的测试,我认为我已经找到了问题:列表显然包含10个相同集合的实例,或10个指向同一集合的指针,等等。 Constructing the list through repeated calls of 通过重复调用构建列表

list.append(set([]))

allowed me to use the syntax above to add elements to single sets. 允许我使用以上语法将元素添加到单个集合中。 So my question is this: what exactly is going on in my first list-construction technique? 所以我的问题是:我的第一个列表构建技术到底发生了什么? It is clear I don't understand the syntax so well. 很明显,我不太了解语法。 Also, is there a better way to intialize an n-element list? 另外,是否有更好的方法初始化n元素列表? I've been using this syntax for a while and this is my first problem with it. 我使用这种语法已有一段时间了,这是我的第一个问题。

You've pretty much summarized the problem yourself -- the X*n syntax makes one instance of X and includes it n times. 您已经亲自总结了很多问题X*n语法构成X的一个实例,并包含n次。 It's not a problem for things like 'a'*10 because it doesn't matter if every character in that string happens to point to the same 'a', but it does for mutable constructions like lists and sets. 对于'a'*10类的问题而言,这并不是问题,因为该字符串中的每个字符是否都指向相同的'a'并不重要,但是对于诸如列表和集合之类的可变结构而言,则确实如此。 You can make n separate sets using a list comprehension: 您可以使用列表推导来制作n个单独的集合:

list = [set() for x in xrange(n)]

Yes, that is correct. 对,那是正确的。 The * syntax is simply copying the reference that many times. *语法只是多次复制引用。 Your method works fine, or you can use a list comprehension to construct that many sets as in: 您的方法可以正常工作,或者您可以使用列表推导来构造多个集合,如下所示:

list = [set([]) for x in xrange(n)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM