lesson7 集合set

概念

作用:去重,关系运算,

可变类型和不可变类型的定义:

可变类型是不可hash类型 不可变类型是可hash类型

集合定义:

集合:可以包含多个元素,用逗号分割, 集合的元素遵循三个原则:
1.每个元素必须是不可变类型(可hash,可作为字典的key)
2.没有重复的元素
3.无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值

主要方法:

1、长度len

pythons={'asdf','bargn','cceao','deryi','eagtbasefv','fargaeg'}
len(pythons)

6

2、成员运算in和not in

'asdf' in pythons

True

3、"|" 合集

pythons2={'asdf','cceao','deryi','eagtbasefv','fargaeg','adsfager'}
pythons | pythons2

{‘adsfager’, ‘asdf’, ‘bargn’, ‘cceao’, ‘deryi’, ‘eagtbasefv’, ‘fargaeg’}

4、&交集

pythons & pythons2

{‘asdf’, ‘cceao’, ‘deryi’, ‘eagtbasefv’, ‘fargaeg’}

5、"-"差集

print(pythons - pythons2)
print(pythons2 - pythons)

{‘bargn’}
{‘adsfager’}

6、 "^"对称差集

pythons ^ pythons2

{‘adsfager’, ‘bargn’}

7、==

pythons == pythons2

False

8、父集:>,>=

pythons3 = {'asdf', 'cceao', 'deryi', 'eagtbasefv', 'fargaeg'}
print(pythons3 > pythons)
print(pythons3 >= pythons)

False
False

9、子集:<,<=

print(pythons3 < pythons)
print(pythons3 <= pythons)

True
True

其它方法

set的方法和object的方法

a = set.__dict__.keys()
b = object.__dict__.keys()
print(a,'\n',b)
dict_keys(['__repr__', '__hash__', '__getattribute__', '__lt__', '__le__',
 '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__init__', '__sub__', 
 '__rsub__', '__and__', '__rand__', '__xor__', '__rxor__', '__or__',  '__ror__', 
 '__isub__', '__iand__', '__ixor__', '__ior__', '__len__',  '__contains__', '__new__',
  'add', 'clear', 'copy', 'discard', 'difference',   'difference_update', 'intersection',
   'intersection_update', 'isdisjoint',   'issubset', 'issuperset', 'pop', '__reduce__',
    'remove', '__sizeof__', 'symmetric_difference', 'symmetric_difference_update',
     'union', 'update', '__doc__']) 
   
 dict_keys(['__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', 
 '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__',
  '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', 
  '__format__', '__sizeof__', '__dir__', '__class__', '__doc__'])

set的独有方法()

print(a - b)
{'__xor__', '__iter__', '__ror__', '__or__', 
'symmetric_difference_update', '__rsub__', 'clear', 
'__rxor__', '__iand__', '__ixor__', 
'difference_update', 'issubset', 'union', 'add', 
'__isub__', '__sub__', '__ior__', '__rand__', 
'update', 'isdisjoint', 'issuperset', '__len__', 'copy', 
'intersection', 'difference', 'intersection_update', 
'__and__', 'symmetric_difference', 'discard', 
'__contains__', 'remove', 'pop'}

练习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值