集合是Python的基本数据类型,是我们工作中经常会用到的数据类型,Python有一系列关于集合的操作,作为一个Pythoner,我们必须要掌握这些操作。
集合是Python的基本数据类型之一,它具有以下几个特点:
集合与列表的区别
列表 | 集合 | |
---|---|---|
顺序 | 有序 | 无序 |
内容 | 可重复 | 不可重复 |
功能 | 用于数据的使用 | 用于数据交集并集差集的获取 |
索引 | 有索引 | 无索引 |
符号 | {} {1,2,3} |
set1 = set()
set1.update([1, 2, 3, 4, 5])
print(set1)
---------------------------
输出结果如下:
{1, 2, 3, 4, 5}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set1.remove('baolan')
print(set1)
-----------------
输出结果如下:
{'rookie', 'jackeylove', 'theshy', 'ning'}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set1.clear()
print(set1)
------------------------
输出结果如下:
set()
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set1.discard('ning')
print(set1)
-----------------
输出结果如下:
{'rookie', 'jackeylove', 'baolan', 'theshy'}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set2 = {'ning', 'baolan'}
set3 = set1.difference(set2)
print(set3)
-----------------------------------------------------
输出结果如下:
{'theshy', 'rookie', 'jackeylove'}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set2 = {'ning', 'baolan'}
set3 = set1.intersection(set2)
print(set3)
----------------------
输出结果如下:
{'ning', 'baolan'}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set2 = {'ning', 'baolan', 'duke'}
set3 = set1.union(set2)
print(set3)
-----------------------------
输出结果如下:
{'theshy', 'rookie', 'ning', 'duke', 'jackeylove', 'baolan'}
set1 = {'theshy', 'rookie', 'jackeylove', 'ning', 'baolan'}
set2 = {'ning', 'baolan', 'duke'}
set3 = {'tian'}
r = set1.isdisjoint(set2)
r1 = set1.isdisjoint(set3)
print(r)
print(r1)
------------------
输出结果如下:
False
True
本文主要介绍了Python中关于集合的相关操作,集合是Python中重要的数据类型,是我们必须掌握的内容。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。