当前位置:首页>行业动态> 正文

python中集合的用法

Python中集合是一种无序、不重复的容器,支持交集、并集、差集等操作,常用set()函数创建。

在Python中,集合是一种无序且不重复的数据结构,它使用大括号{} 或者set() 函数来创建,以下是关于Python中集合的符号的详细解释:

1、创建空集合:

使用大括号{} 创建一个空集合:

“`python

empty_set = {}

“`

使用set() 函数创建一个空集合:

“`python

empty_set = set()

“`

2、创建包含元素的集合:

使用大括号{} 将元素括起来创建一个集合:

“`python

my_set = {1, 2, 3}

“`

使用set() 函数将元素作为参数传递给函数来创建一个集合:

“`python

my_set = set([1, 2, 3])

“`

3、添加元素到集合:

使用add() 方法将单个元素添加到集合中:

“`python

my_set.add(4)

“`

使用update() 方法将一个可迭代对象(如列表、元组等)中的元素添加到集合中:

“`python

my_set.update([4, 5, 6])

“`

4、删除集合中的元素:

使用remove() 方法删除指定元素:

“`python

my_set.remove(4)

“`

使用discard() 方法删除指定元素,如果元素不存在则不会引发错误:

“`python

my_set.discard(4)

“`

使用pop() 方法删除并返回指定索引处的元素,如果集合为空则会引发错误:

“`python

my_set.pop()

“`

5、集合运算:

交集(Intersection):使用& 运算符或intersection() 方法获取两个集合的交集:

“`python

set1 = {1, 2, 3}

set2 = {2, 3, 4}

intersection = set1 & set2

# or

intersection = set1.intersection(set2)

“`

并集(Union):使用| 运算符或union() 方法获取两个集合的并集:

“`python

set1 = {1, 2, 3}

set2 = {2, 3, 4}

union = set1 | set2

# or

union = set1.union(set2)

“`

差集(Difference):使用 运算符或difference() 方法获取两个集合的差集:

“`python

set1 = {1, 2, 3}

set2 = {2, 3, 4}

difference = set1 set2

# or

difference = set1.difference(set2)

“`