当我使用时
a = {}
和
a = set()
有时我看到使用如下:
a = set([])
它们是相同的吗?它们之间有什么区别?
我问这个问题是因为
a = set(range(5))
b = {0,1,2,3,4}
a == b
>>> True
默认情况下,{}
在 Python 中代表一个空字典。然而,花括号既用于 dict
字面值,也用于 set
字面值。参见以下示例:
empty_set = set()
non_empty_set = {1,2,3}
empty_dict = {}
empty_dict2 = dict()
non_empty_dict = {"a": 1}
避免使用
a = set([]) # instead use a = set()
a = {}
print(f"type of a={type(a)}")
输出:
type of a=<class 'dict'>
b = {1, 2, 3}
print(f"type of b={type(b)}")
c = {"some_key": "some_value"}
print(f"type of c={type(c)}")
输出:
type of b=<class 'set'>
type of c=<class 'dict'>
集合和字典是两种不同的数据结构。您可以在此处详细了解它们:Python初学者指南:列表,元组,字典,集合
{}
字面上将是一个包含键值对的字典,而 set()
则是一个仅包含纯值的集合。当使用多个元素时,它们的字面值将根据是否包含键值对来区分。例如,{1: 'a', 2: 'b'}
与 {1, 2}
。
它们不是同一个东西。
{}
创建一个空字典(但 {1,2,3}
创建一个包含3个元素的集合:1、2、3)
set()
创建一个空集合