零基础入门学习Python(14):集合set()
集合里面所有元素都是唯一的,而且,集合是无序的,不支持索引
创建集合有两种方式:
1)直接把一堆元素用花括号括起来
2)使用工厂函数set()
>>> num = {} #直接使用空的花括号创建的是一个字典类型的对象
>>> type(num)
<class 'dict'>
>>> num1 = {1,2,3,4,5} #创建一个集合
>>> type(num1)
<class 'set'>
>>> num2 = {1,2,3,4,2,3,4} #集合会自动剔除相同的元素
>>> num2
{1, 2, 3, 4}
>>> num3 = set() #使用工厂函数创建一个空集合
>>> num3
set()
>>> num4 = set([1,2,3,4,5]) #set()函数的参数是一个可迭代对象
>>> num4
{1, 2, 3, 4, 5}
>>> num5 = set([1,2,3,4,'hello'])
>>> num5
{1, 2, 3, 4, 'hello'}
访问集合中的值:可以通过in和not in 判断一个元素是否在集合中已经存在,也可以使用for把集合中的数据一个个读取出来
>>> 2 in num5
True
>>> 5 not in num5
True
>>> num6 = list(num5) #需要先把集合转换成列表,再通过索引一个一个读取
>>> for i in range(len(num6)):
print(num6[i],end = ' ')
1 2 3 4 hello
集合中常用的几个函数
>>> num5 = set([1,2,3,4,'hello'])
>>> num5.remove(4) #从集合中移除元素,如果要移除的元素不存在,则会出错
>>> num5
{1, 2, 3, 'hello'}
>>> num5.add('Jessica') #向集合添加元素
>>> num5
{1, 2, 3, 'Jessica', 'hello'}
>>> num4 = set([1,2,3,4,5])
>>> num4 & num5 #集合中的'与',包含num4和num5中共同的元素
{1, 2, 3}
>>> num4 | num5 #集合中的'或',包含num4和num5中所有的元素
{1, 2, 3, 4, 5, 'hello', 'Jessica'}
>>> num4 ^ num5 #集合中的异或,包含只在num4和只在num5中的元素
{4, 'Jessica', 'hello', 5}
>>> num4 - num5 #包含在num4中但不在num5中的元素
{4, 5}
>>> num3 = {1,2,3}
>>> num3 <= num4 #集合num3包含于集合num4,两个集合可以相等
True
>>> num4 >= num3 #集合num4包含集合num3,两个集合可以相等
True
>>> num4.pop() #从集合中弹出任意一个元素
1
>>> num4
{2, 3, 4, 5}
>>> num4.clear() #清空集合
>>> num4
set()