Python常用数据结构之--集合set--Loxida

Python常用数据结构之–集合set

1、集合的定义:

①无序的唯一对象集合

②用大括号{}包围,对象相互之间使用逗号分隔

③集合是动态的,可以随时添加或删除元素

④集合是异构的,可以包含不同类型的数据

2、集合的创建

(1)通过使用大括号{}填充元素
s1 = {1, 2, 3, 'a', 'b', 'c'}
print(type(s1), s1)
(2)使用构造方法创建集合
s2 = set('hello')
print(type(s2),s2)
s3 = set()   # 空集合
print(type(s3),s3)
(3)使用集合推导式
s4 = {i for i in range(1, 10) if i % 2 == 0}
s5 = {i for i in range(1, 10)}
print(type(s4), s4)
print(type(s5), s5)
#注意不要单独使用 { }来创建空集合,这是字典类型
s = {}
print(type(s), s)

3、集合成员检测

①in:判断元素是否在集合中存在

②not in:判断元素是否在集合中不存在

s = {1, 2, 3, 'a', 'b', 'c'}
print('a' in s)
print(3 not in s)

4、集合的方法

(1)add(item):

1)将单个对象添加到集合中

#add() 添加单个对象到集合中
s = {1, 2, 3}
s.add('a')
s.add('hello')
print(s)
(2)update(iterable):

1)批量添加来自可迭代对象中的所有元素,入参为可迭代对象iterable

#update()方法,批量添加来自可迭代对象中的所有元素
l1 = [1, 2, 3]
t1 = ('a', 'b', 'c')
s1 = {'hello', 'world'}
s2 = {'happy'}
#批量添加列表中的元素
s1.update(l1)
print(type(s1), s1)
#批量添加元组中的元素
s1.update(t1)
print(type(s1), s1)
#批量添加集合中的元素
s1.update(s2)
print(type(s1), s1)
(3)remove(item):

1)从集合中移除指定元素 item,如果item不存在于集合 中 则会引发 KeyError

#remove()方法,从集合中移出指定元素,指定元素必须在集合里
s3 = {1, 2, 3, 4, 'a', 'b', 'c'}
s3.remove(4)
print(s3)
#删除不存在的元素
s3.remove('d')
print(s3)
(4)discard(item):

1)从集合中移除指定对象 item,元素 item 不存在没影响, 不会抛出 KeyError 错误。

#discard(),从集合中移出指定元素,指定元素可以不在集合里
s4 = {1, 2, 3, 4, 'a', 'b', 'c'}
s4.discard(4)
print(s4)
#删除不存在的元素
s4.discard('d')
print(s4)
(5)pop():

1)随机从集合中移除并返回一个元素

2)无入参,返回被移除的元组;如果集合为空则会引发KeyError。

#pop(),随机从集合中移出并返回一个元素,集合不能为空
s5 = {1, 2, 3, 4, 'a', 'b', 'c'}
s5.pop()
print(s5)
(6)clear()

1)清空集合,移除所有元素,无入参

#clear(),清空集合,移出所有元素,无入参,集合可为空
s6 = {1, 2, 3, 4, 'a', 'b', 'c'}
s6.clear()
print(s6)

5、集合运算

(1)交集运算
#交集运算intersection(),操作符:&
s7 = {1, 2, 3, 5}
s8 = {1, 2, 6, 8}
print(s7.intersection(s8))
print(s7 & s8)
(2)并集运算
#并集运算union(),操作符:|
print(s7.union(s8))
print(s7 | s8)
(3)差集运算
#差集运算difference,操作符:-
print(s7.difference(s8))
print(s7 - s8)
print(s8.difference(s7))
print(s8 - s7)

6、集合推导式

①类似列表推导式,同样集合支持集合推导式

②语法:{x for x in … if …}

s9 = {i for i in range(1, 10)}
#有判断条件
s10 = {i for i in range(1, 10) if i % 2 != 0}
print(s9)
print(s10)