python之集合类型

找两个列表当中的相同元素

friends1 = ['zero', 'kevin', 'jason', 'egon']
friends2 = ['jy', 'kevin', 'jason', 'egon']

l = []
for x in friends1:      #for循环太复杂了
    if x in friends2:
        l.append(x)
print(l)

2、定义:

 在{}内用逗号分隔开多个元素,多个元素满足以下三个条件:

     1、集合内的元素必须是不可变类型

​     2、集合内元素无序

​     3、集合内元素不能重复,重复只能留一个

s = {}       # 默认空字典
s = {1,2}       # s = set({1,2})
s = {1,[1,2]} 错误
s = {1,'a','z',4,7}    #  集合内元素无序
s = {1,21,1,1,1}        # 集合内元素没有重复
s = set()       # 定义空集合

3、类型转换

set('hellollllll')   # 相当于调用For循环得到“heol”,本身就是无序的
print(set([1,1,1,1,1,1]))    # 返回{1}
print(set([1,1,1,1,1,1,[1,2]]))   # 报错
print(set({'k1':1,'k2':2}))   # 返回的是key

4、内置方法

关系运算符

friends1 = {'zero', 'kevin', 'jason', 'egon'}
friends2 = {'jy', 'ricky', 'jason', 'egon'}

4.1 求交集:两者共同的好友

res = friends1 & friends2
print(res)

print(friends1.intersection(friends2))

4.2 求并集:两者所有的好友

a = friends1 | friends2
print(a)

print(friends1.union(friends2))

4.3 求差集:取friend1独有的好友

print(friends1 - friends2)

print(friends1.difference(friends2))  #求那个调用哪个

求差集:取friend1独有的好友

print(friends2 - friends1)

print(friends2.difference(friends1))

4.4 求两个用户独有的好友们

print(friends1 ^ friends2)

print(friends1.symmetric_difference(friends2))  # 求对称的不同

4.5 父子集:包含的关系

s1 = {1, 2, 3}
s2 = {1, 2, 4}

不存在包含关系,下面比较均为False

print(s1 > s2)
print(s1 < s2)
s11 = {1, 2, 3}
s22 = {1, 2}
print(s11 > s22)  # 当s11大于或者等于s22时,才能说s11是s22的爹

print(s11.issuperset(s22))  #s1 > s2
print(s22.issubset(s11)) # s2 < s1  =>True
s1 = {1, 2, 3}
s2 = {1, 2, 3}
print(s1 == s2)  # s1与s2互为父子

print(s1.issuperset(s2))
print(s2.issuperset(s1))

去重

1、只能针对不可变类型去重

print(set([1, 1, 1, 2, 2, 3]))

2、可以去重但无法保证原来的顺序

l = [1, 'a', 'b', 'z', 1, 1, 2, 3, 4, 2]
l = list(set(l))
print(l)

3、自己去重的代码

l=[
    {'name':'lili','age':18,'sex':'male'},
    {'name':'jack','age':73,'sex':'male'},
    {'name':'tom','age':20,'sex':'female'},
    {'name':'lili','age':18,'sex':'male'},
    {'name':'lili','age':18,'sex':'male'},
]
new_l = []
for dic in l:
    if dic not in new_l:
        new_l.append(dic)
print(new_l)

需要掌握的内置方法

  1、discard:如果集合当中有这个成员,则把这个成员删掉

s = {1,2,3}    # 删除元素不存在do nothing
s.discard(4)  # 不会报错
s.remove(4)  # 会报错

  2、update:更新集合,也就是把新集合加进去,然后做个去重

s.update({1,3,5})
print(s)

  3、pop

s.pop()  #按照索引删除
print(s)

  4、add

s.add(6)
print(s)

  5、其余方法全为了解

res=s.isdisjoint({3,4,5,6}) # 两个集合完全独立、没有共同部分,返回True
print(res)


s.difference_update({3,4,5}) # s=s.difference({3,4,5}),也就是说先求差集,然后把集合更新去重,成为新的集合
print(s)