所以,我知道这个,
a = {} # dict
构造一个空字典。现在,我也捡到了这个,
b = {1, 2, 3} # set
创建一个集合。这很容易验证,因为,
>>>print(type(a))
<class 'dict'>
>>>print(type(b))
<class 'set'>
虽然我理解它的作用,但我看不出为什么我们对空字典使用“集合表示法”。我试图在 set
中找到有关其背后逻辑的更多信息。和 dict
手册的部分,但遗憾的是,我没有从中得到任何东西。
谁能向我解释为什么我们会这样做?是因为历史原因,还是我遗漏了一些明显的东西?
最佳答案
Python 2 中没有 set literals,历史上花括号仅用于字典。集合可以从列表(或任何可迭代对象)中产生:
set([1, 2, 3])
set([i for i in range(1, 3)])
Python 3 引入了集合字面量和推导式(参见 PEP-3100),这使我们能够避免中间列表:
{1, 2, 3}
{i for i in range(1, 3)}
然而,由于向后兼容,空集形式被保留给字典使用。来自 [Python-3000] sets in P3K? 的引用资料状态:
I'm sure we can work something out --- I agree,
{}
for empty set and{:}
for empty dict would be ideal, were it not for backward compatibility. I liked the "special empty object" idea when I first wrote the PEP (i.e., have{}
be something that could turn into either a set or dict), but one of the instructors here convinced me that it would just lead to confusion in newcomers' minds (as well as being a pain to implement).
following message更好地描述这些规则:
I think Guido had the best solution. Use
set()
for empty sets, use{}
for empty dicts, use{genexp}
for set comprehensions/displays, use{1,2,3}
for explicit set literals, and use{k1:v1, k2:v2}
for dict literals. We can always add{
/}
later if demand exceeds distaste.
关于python - dict和set之间的区别(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370599/