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

768
2024/8/29 15:31:25
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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 中的基本操作。你可以根据需要进行更多的集合操作。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何在Python中实现代码封装