python-集合用法(52)

本文详细介绍了Python中集合的基本操作,包括创建、元素遍历、长度获取、交集、并集、差集等,并通过实例展示了如何使用这些操作。同时,文章还解释了集合的特性及其在实际编程中的应用。
#转自https://www.jianshu.com/c/00c61372c46a网址
#集合相当于无值的字典,所以也用{}表示
>>> myset = set('hello')
>>> myset
{'e', 'o', 'h', 'l'}
>>> len(myset)
4
>>> for ch in myset:
...     print(ch)
...
e
o
h
l
>>> aset = set('abc')
>>> aset
{'c', 'a', 'b'}
>>> bset = set('cde')
>>> bset
{'c', 'e', 'd'}
>>> aset & bset #交集
{'c'}
>>> aset.intersection(bset) #交集
{'c'}
>>> aset | bset #并集
{'e', 'd', 'a', 'c', 'b'}
>>> aset.union(bset)    #并集
{'e', 'd', 'a', 'c', 'b'}
>>> aset - bset #差集
{'a', 'b'}
>>> bset - aset
{'e', 'd'}
>>> bset.difference(aset)   #差集
{'e', 'd'}
>>> aset.difference(bset)
{'a', 'b'}
>>> aset.add('new')
>>> aset
{'c', 'a', 'new', 'b'}
>>> aset.update(['aaa','bbb'])
>>> aset
{'a', 'c', 'aaa', 'b', 'new', 'bbb'}
>>> aset.remove('bbb')
>>> aset
{'a', 'c', 'aaa', 'b', 'new'}
>>> cset = set('abcde')
>>> cset
{'e', 'd', 'a', 'c', 'b'}
>>> dset = set('bcd')
>>> dset
{'c', 'b', 'd'}
>>> cset.issuperset(dset)   #cset是dset的超集吗?
True
>>> cset.issubset(dset)     #cset是dset的子集吗?
False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值