英文:
How does this code manage to add new elements to a set?
问题
他们首先初始化了名为rows
的列表:
rows = [set() for _ in range(9)]
这意味着它创建了一个 [set(), ..., set()]
格式的列表。但后来在代码中,他们通过以下方式向这些集合添加元素:
rows[i].add(num)
从我的理解来看,集合是不可变的,那么它是如何能够以这种方式持续更新的呢?
英文:
I was working on a leetcode problem and one of the answers confused me on how it works. They first initialize the list, rows
:
rows = [set() for _ in range(9)]
which I understand as creating a list of [set(), ..., set()]
format. But later in the code they add to these sets by calling:
rows[i].add(num)
From my understanding, sets are immutable so how is that the set is able to be continuously updated in such a manner?
答案1
得分: 0
set
不是不可变的。set
的值必须是不可变的(更准确地说,是可散列的,如果它们实际上不是不可变的,则被视为不可变),但只有frozenset
是真正不可变的。set
被设计为可变的。
英文:
set
s aren't immutable. The values of a set
must be immutable (more precisely, hashable and treated as immutable if they aren't actually immutable), but only frozenset
is actually immutable. set
s are intended to be mutable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论