(四)集合
目录
4.1集合
集合:可变的数据类型,里面的元素是不可变数据类型,无序,不重复
不可变数据类型:整型,字符串,元组,布尔值
集合的表示:s = set(['a','b','c'])
s = {'1','2'.'3'}
4.2集合的操作
a.增加 add update
#增加
#add
set1 = set(['as','ad','af'])
set1.add('aaaaa')
print(set1) #增加的位置随机
#updata
set1.update('abc') #'a''b''c'位置随机
print(set1)
b.删除
#删除
# set1 = {'as','ad','af'}
#pop 随机删除,有返回值
set1.pop()
print(set1)
print(set1.pop())
#remove
set1.remove('as')
print(set1)
#clear
set1.clear()
print(set1)#空集合 set()
c.查
//查
for i in set1:
print(i)
set1 = {1,2,4,5}
set2 = {4,5,6,7}
//交集
print(set1 & set2)
print(set1.intersection(set2))
{4, 5}
{4, 5}
//并集
print(set1 | set2)
print(set1.union(set2))
{1, 2, 4, 5, 6, 7}
{1, 2, 4, 5, 6, 7}
//反交集:不同时在set1和set2
print(set1 ^ set2)
print(set1.symmetric_difference(set2))#{1, 2, 6, 7}
{1, 2, 6, 7}
{1, 2, 6, 7}
//set1独有的
print(set1 - set2)
print(set1.difference(set2))
{1, 2}
{1, 2}
set1 = {1,2,4,5}
set2 = {1,2,4,5,6,7}
//set1是set2的子集
print(set1 < set2)
print(set1.issubset(set2))
True
True
//set2是set1的超集
print(set2 > set1)
print(set2.issuperset(set1))
True
True
d.去重
li = {1,1,3,3,2,2}
set1 = set(li)
print(list(set1))
e.frozenset不可变集合,让集合变成不可变类型
s = frozenset('asdf')
print(s,type(s)) #位置随机frozenset({'s', 'd', 'f', 'a'}) <class 'frozenset'>
f.key与value互换
dic_new = {value:key for key,value in dic.items()}
dic_new = dict(zip(c.values(),c.keys()))