温馨提示×

python怎么创建一个集合

小亿
96
2024-01-19 15:41:07
栏目: 编程语言

要创建一个集合,可以使用大括号{}将元素括起来,并使用逗号分隔元素。

以下是创建一个集合的示例代码:

# 创建一个空集合
empty_set = set()
print(empty_set)  # 输出 set()

# 创建一个包含元素的集合
my_set = {1, 2, 3, 4, 5}
print(my_set)  # 输出 {1, 2, 3, 4, 5}

# 创建一个包含重复元素的集合
my_set_with_duplicates = {1, 2, 3, 3, 4, 4, 5}
print(my_set_with_duplicates)  # 输出 {1, 2, 3, 4, 5}

# 使用set()函数创建集合
my_set_using_function = set([1, 2, 3, 4, 5])
print(my_set_using_function)  # 输出 {1, 2, 3, 4, 5}

请注意,集合是无序的,且不允许包含重复的元素。如果创建集合时有重复的元素,集合会自动去除重复项。

0