将值添加到集合列表中的元素
我正在使用 python,并且有一个集合列表,其构造如下:
list = [set([])]*n
...其中 n 是我想要在列表中出现的集合数。我想向列表中的特定集合添加一个值。说吧,第二盘。我尝试过
list[1].add(value)
但这会将值添加到列表中的每个集中。这种行为对我来说非常不直观。通过进一步的测试,我想我已经发现了问题:列表显然包含同一个集合的10个实例,或者十个指向同一个集合的指针,或者其他东西。通过重复调用构建列表
list.append(set([]))
允许我使用上面的语法将元素添加到单个集合中。所以我的问题是:我的第一个列表构建技术到底发生了什么?很明显我不太了解语法。另外,有没有更好的方法来初始化 n 元素列表?我使用这种语法已经有一段时间了,这是我遇到的第一个问题。
I'm using python, and I have a list of sets, constructed like this:
list = [set([])]*n
...where n is the number of sets I want in the list. 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. 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? I've been using this syntax for a while and this is my first problem with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您自己已经大致总结了该问题 -
X*n
语法生成 X 的一个实例并包含它 n 次。对于像'a'*10
这样的东西来说这不是问题,因为如果该字符串中的每个字符都指向同一个 'a' 并不重要,但对于像列表和套。您可以使用列表推导式创建 n 个单独的集合:You've pretty much summarized the problem yourself -- the
X*n
syntax makes one instance of X and includes it n times. 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. You can make n separate sets using a list comprehension:是的,这是正确的。 * 语法只是多次复制引用。您的方法工作正常,或者您可以使用列表理解来构造多个集合,如下所示:
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: