在Python中,您可以使用大括号 {}
或者内置的 set()
函数来创建一个集合(set)
方法1:使用大括号 {}
my_set = {1, 2, 3, 4, 5}
print(my_set) # 输出:{1, 2, 3, 4, 5}
方法2:使用 set()
函数
my_set = set([1, 2, 3, 4, 5])
print(my_set) # 输出:{1, 2, 3, 4, 5}
注意:空的大括号 {}
是用来创建字典(dictionary)的,而不是集合(set)。要创建一个空集合,请使用 set()
函数,如下所示:
empty_set = set()
print(empty_set) # 输出:set()
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Python中set()函数如何创建集合