这段代码是如何成功地向集合中添加新元素的?

huangapple go评论137阅读模式
英文:

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设计为可变的。

英文:

sets 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. sets are intended to be mutable.

huangapple
  • 本文由 发表于 2023年6月13日 07:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460937.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定