Python之集合

集合

定义

在{}内用逗号分隔开多个元素,多个元素满足一下三个条件:
1. 集合内元素必须为不可变类型
2. 集合内元素无序
3. 集合内元素没有重复
s = {1,2} #s = set({1,2})

s != {1,[1,2]} # 集合内元素必须为不可变类型
s = {1,‘a’,‘z’,‘b’,4.7} # 集合内元素无序
s = {1,1,1,1,1,1,‘a’,‘b’} # 集合内元素没有重复
print(s)

了解

s = {} # 默认是空字典
定义空集合:s= set()

类型转换

s = set('helllllllo')
print(s, type(set))
>>>{'o', 'l', 'h', 'e'} <class 'type'>

s = set([1,1,1,11,1,22])
print(s, type(set))
>>>{1, 11, 22} <class 'type'>

内置方法

friends1 = {"zero","kevin","jason","egon"} # 用户1的好友们 
friends2 = {"Jy","ricky","jason","egon"}   # 用户2的好友们

两个集合的关系如下图所示
在这里插入图片描述

1.合集/并集(|):求两个用户所有的好友(重复好友只留一个)

friends1 | friends2
{'kevin', 'ricky', 'zero', 'jason', 'Jy', 'egon'}

print(friends1.union(friends2))
{'Jy', 'kevin', 'egon', 'zero', 'ricky', 'jason'}

2.交集(&):求两个用户的共同好友

>>> friends1 & friends2
>>> print(friends1.intersection(friends2))
{'jason', 'egon'}

3.差集(-):

>>> friends1 - friends2 # 求用户1独有的好友
>>> print(friends1.difference(friends2)) #friends1.difference(friends2)不会直接改变friends1的值,但是friends1.difference_update(friends2)会改变friends1的原值 以下同理
{'kevin', 'zero'}
>>> friends2 - friends1 # 求用户2独有的好友
>>> print(friends2.difference(friends1))
{'ricky', 'Jy'}

4.对称差集(^) # 求两个用户独有的好友们(即去掉共有的好友)

>>> (friends1 - friends2) | (friends2 - friends1)
>>> (friends1 | friends2) - (friends1 & friends2)
>>> friends1 ^ friends2
>>> print(friends1.symmetric_difference(friends2))
{'kevin', 'zero', 'ricky', 'Jy'}

5.值是否相等(==)

>>> friends1 == friends2
False

6.父集:一个集合是否包含另外一个集合

6.1 包含则返回True
>>> {1,2,3} > {1,2}
>>>print({1,2,3}.isuperset({1,2}))
True
>>> {1,2,3} >= {1,2}
>>> print({1,2}.issubset({1,2,3}))
True
6.2 不存在包含关系,则返回False
>>> {1,2,3} > {1,3,4,5}
False
>>> {1,2,3} >= {1,3,4,5}
False

7.子集

>>> {1,2} < {1,2,3}
True
>>> {1,2} <= {1,2,3}
True

集合去重复有局限性

  1. 只能针对不可变类型
  2. 集合本身是无序的,去重之后无法保留原来的顺序

其他操作

1.长度

>>> s={'a','b','c'}
>>> len(s)
3

2.成员运算

>>> 'c' in s
True

3.循环

>>> for item in s:
...     print(item)
... 
c
a
b

其他内置方法

其他内置方法

s = {1, 2, 3}
res = s.discard(3) #删除元素不存在则报错
print(s, res)
>>> {1, 2} None

s = {1, 2, 3}
res = s.remove(4)
print(s, res)
报错

因此,discard要比remove兼容性更好

s = {1, 2, 3}
res = s.pop()
print(s, res)
>>> set.pop()随机删除值
s1 = {1, 2, 3}
s2 = {3, 4, 5}
res = s1.isdisjoint(s2)  # 判断两个集合是否完全独立
print(res, s1, s2)
>>>False {1, 2, 3} {3, 4, 5}
s = {1, 2, 3}
res = s.add(4)  # 判断两个集合是否完全独立
print(res, s)
>>>None {1, 2, 3, 4}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值