温馨提示×

set()函数在Python中的基本操作

小樊
83
2024-08-29 14:13:11
栏目: 编程语言

set() 是 Python 中的一个内置函数,用于创建一个新的集合(set)。集合是一个无序的不重复元素序列。

以下是 set() 函数的基本操作:

  1. 创建一个空集合:
empty_set = set()
print(empty_set)  # 输出:set()
  1. 使用可迭代对象(如列表、元组等)创建集合:
my_list = [1, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set)  # 输出:{1, 2, 3, 4, 5},注意重复的元素被去除了
  1. 集合的添加和删除操作:
my_set = {1, 2, 3}
my_set.add(4)  # 添加元素 4
print(my_set)  # 输出:{1, 2, 3, 4}

my_set.remove(2)  # 删除元素 2
print(my_set)  # 输出:{1, 3, 4}
  1. 集合的交集、并集、差集和对称差集操作:
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

intersection = set_a.intersection(set_b)  # 交集
print(intersection)  # 输出:{3, 4}

union = set_a.union(set_b)  # 并集
print(union)  # 输出:{1, 2, 3, 4, 5, 6}

difference = set_a.difference(set_b)  # 差集
print(difference)  # 输出:{1, 2}

symmetric_difference = set_a.symmetric_difference(set_b)  # 对称差集
print(symmetric_difference)  # 输出:{1, 2, 5, 6}

这些是 set() 函数在 Python 中的基本操作。你可以根据需要进行更多的集合操作。

0