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

   2024-09-30 4950
核心提示:set() 是 Python 中的一个内置函数,用于创建一个新的集合(set)。集合是一个无序的不重复元素序列。以下是 set() 函数的基本操

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

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

创建一个空集合:
empty_set = set()print(empty_set)  # 输出:set()
使用可迭代对象(如列表、元组等)创建集合:
my_list = [1, 2, 3, 4, 4, 5]my_set = set(my_list)print(my_set)  # 输出:{1, 2, 3, 4, 5},注意重复的元素被去除了
集合的添加和删除操作:
my_set = {1, 2, 3}my_set.add(4)  # 添加元素 4print(my_set)  # 输出:{1, 2, 3, 4}my_set.remove(2)  # 删除元素 2print(my_set)  # 输出:{1, 3, 4}
集合的交集、并集、差集和对称差集操作:
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 中的基本操作。你可以根据需要进行更多的集合操作。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号