python基础知识之集合

集合是无序的、不重复的数据集合,它本身是可变的,但里面的元素是不可变类型(这里要注意,即使是含有列表的元组也不可以,必须是完全不可变类型)

#创建集合 使用set()来创建,
s1 = set({2,5,'hello',(2,5,'world')})
print(s1)
{(2, 5, 'world'), 2, 5, 'hello'}
#增
s1 = set({2,5,'hello',(2,5,'world')})
s1.add('随机')  #添加的位置是随机的
print('输出结果是:')
print(s1)
s1.update('分解元素') #迭代的方式,即把元素拆分开来后随机添加到集合中
print(s1)
输出结果是:
{2, 5, 'hello', '随机', (2, 5, 'world')}
{2, 5, 'hello', '随机', '素', '分', (2, 5, 'world'), '解', '元'}
#删
s1 = set({2,5,'hello',(2,5,'world')})
res = s1.pop()#随机删除,并返回删除的值,()里不能添加索引,因为集合是无序的,没有索引
print('输出结果是:')
print(s1,res)
s1.remove(5)#删除指定的值,无返回值,这里删除了数字5
print(s1)
s1.clear()#清空集合
print(s1)
del s1 #删除集合
输出结果是:
{2, 5, 'hello'} (2, 5, 'world')
{2, 'hello'}
set()

对于集合来讲有几种运算方法:交集、并集、差集、反交集、子集、超集

s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('交集:',s1 & s2) #可用&或者intersection,输出一个新的集合,包含共同拥有的元素
print('交集:',s1.intersection(s2))
print('并集:',s1 | s2) #可用|或者union,输出一个新的集合,包含两个集合中所有的元素(去重)
print('并集:',s1.union(s2))
print('差集:',s1 - s2) #可用 - 或者difference,输出一个新的集合,包含前一个集合中除去共有的元素
print('差集:',s1.difference(s2))
print('反交集:',s1 ^ s2) #可用^或者 symmetric_difference,输出一个新的集合,包含两个集合中除去共有的元素后剩余的所有元素
print('反交集:',s1.symmetric_difference(s2))
交集: {3, 4, 5}
交集: {3, 4, 5}
并集: {1, 2, 3, 4, 5, 6, 7}
并集: {1, 2, 3, 4, 5, 6, 7}
差集: {1, 2}
差集: {1, 2}
反交集: {1, 2, 6, 7}
反交集: {1, 2, 6, 7}
#子集与超集,简单来讲就是一个集合中的元素包含另一个集合中所有的元素,则“大的”集合叫超集,“小的”叫子集
s1 = {1,2,3}
s2 = {1,2,3,4,5}
print(s1.issubset(s2)) #输出为True,s1是s2的子集
print(s2.issuperset(s1))#输出为True,s2是s1的超集
True
True

使用frozenset(‘集合名’),可以把集合变成不可变集合

猜你喜欢

转载自blog.csdn.net/Grim777/article/details/81483692