006_集合

1,集合:
  1.1,集合与字典一样也是用{},但是仅仅是dic = {}创建是字典
print(type({}))     #结果:<class 'dict'>
set1 = {1, 2, 3}
print(type(set1))   #结果:<class 'set'>
  1.2可变的数据类型,但是它里面的元素必须是不可变的数据类型。
  1.3集合元素无序,不重复。
#以下错误的写法list是可变的数据类型
set1 = {1, 2, [4, 5], {'name': 'py'}, (3, 4)}
#TypeError: unhashable type: 'list'
2,创建集合
set1 = set()
set2 = set({1, 2, 3})
print(type(set1))      #结果:<class 'set'>
print(type(set2))      #结果:<class 'set'>

set3 = {1 ,2, 3}
print(type(set3))       #结果:<class 'set'>
3,增加
  3.1,add() 增加,位置随机,添加已有的无效
set1 = {1, 2, 3, '女神'}
set1.add('女神')
print(set1)       #结果:{1, 2, 3, '女神'}
  3.2,update() 迭代(分解)随机位置增加,添加已有的无效
set1 = {1, 2, 3, '女'}
set1.update('女神')
print(set1)         #结果:{'女', 1, 2, 3, '神'}
4,删除
  4.1,pop() 随机删除并返回值,set为空则报错
set1 = {1, 2, 3, '女'}
print(set1.pop())
print(set1)
  4.2,remove()  按元素删除,元素不存在则报错
set1 = {1, 2, 3, '女'}
set1.remove('女')
print(set1)
5,清空,删除集
set1 = {1, 2, 3, '女'}
set1.clear()    #清空set
print(set1)     #结果:set()

del set1        #删除set
6,查
    集合是无序的,每次输出顺序不一样
set1 = {1, 2, 3, '女'}
for i in set1:
    print(i,end=' ')    #结果:女 1 2 3
7,交集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = set1 & set2
print(set3)         #>>>{4, 5}

print(set1.intersection(set2))  #>>>{4, 5}
8,并集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 | set2)        #>>>{1, 2, 3, 4, 5, 6, 7, 8}

print(set1.union(set2))   #>>>{1, 2, 3, 4, 5, 6, 7, 8}
9,反交集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 ^ set2)      #>>>{1, 2, 3, 6, 7, 8}

print(set1.symmetric_difference(set2))   #>>>{1, 2, 3, 6, 7, 8}
10,差集
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1 - set2)      #>>>{1, 2, 3}     #set1独有的

print(set1.difference(set2))    #>>>{1, 2, 3}
11,子集
set1 = {1, 2, 3}
set2 = {1, 2, 3, 7, 8}
print(set1 < set2)      #>>>True    #set1是set2的子集

print(set1.issubset(set2))  #>>>True
12,超集
set1 = {1, 2, 3}
set2 = {1, 2, 3, 7, 8}
print(set2 > set1)      #>>>True      #set2是set1的子集

print(set2.issuperset(set1))  #>>>True
13,通过集合完成列表去重
lis = [1, 3, 4, 3, 5, 5, 2]
set1 = set(lis)
print(set1)         #>>>{1, 2, 3, 4, 5}
lis = list(set1)
print(lis)          #>>>[1, 2, 3, 4, 5]
14,将集合变成不可变集合
set1 = frozenset({1,2,3})
print(set1,type(set1))      #>>>frozenset({1, 2, 3}) <class 'frozenset'>

s = frozenset('colour')
print(s,type(s))        #>>>frozenset({'l', 'u', 'c', 'o', 'r'}) <class 'frozenset'>

s = frozenset([1, 3, 4, 3, 5, 5, 2])
print(s,type(s))        #>>>frozenset({1, 2, 3, 4, 5}) <class 'frozenset'>

  

posted @ 2019-03-05 19:49  冰羽~zZ  阅读(140)  评论(0编辑  收藏  举报