在Python中,set
是一种集合类型,它是一个无序的、可变的集合,包含不重复的元素。set
是通过大括号 {}
来创建的,或者使用 set()
函数。
下面是一些常用的set
操作:
-
创建一个空的
set
:my_set = set()
-
创建一个有初始元素的
set
:my_set = {1, 2, 3}
-
添加元素到
set
中:my_set.add(4)
-
从
set
中删除元素:my_set.remove(3)
-
求两个
set
的交集:set1 = {1, 2, 3} set2 = {2, 3, 4} intersection = set1.intersection(set2)
-
求两个
set
的并/差集:set1 = {1, 2, 3} set2 = {2, 3, 4} union = set1.union(set2) //差集 union2 = set1.differenc(set2)