少说话多写代码之Python学习058——标准模块(集合)
2018-12-09 18:14
218 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yysyangyangyangshan/article/details/84930245
来看看集合(set)的使用。集合类set在sets模块中,Python2.3之后,集合类已经成为语言的一部分,无需再导入sets模块。
先看看简单的使用,
[code]print(set(range(10))) 输出 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
集合中重复值是被忽略的,比如这样,
[code]single=set([1,6,7,8,6,6,6,8]) print(single) 输出 {8, 1, 6, 7}
元素的顺序,不会依照声明时的顺序,
[code]sort = set(['陆小凤','西门吹雪','叶孤城']) print(sort) 输出 {'叶孤城', '西门吹雪', '陆小凤'}
集合可以做一些运算,定义了集合seta和setb,做如下运算,
比如并集
[code]seta=set([10,20,40]) setb=set([30,40,50]) setc = seta.union(setb) print(setc) 输出 {50, 20, 40, 10, 30}
按位与,
[code]print(seta |setb) 输出 {50, 20, 40, 10, 30}
其他一些运算,
[code]setd =seta&setb print(setd.issubset(seta)) 输出:True print(setd <=seta) 输出:True print(setd.issuperset(seta)) 输出:False print(seta.intersection(setb)) 输出:{40} print(seta&setb) 输出:{40} print(seta.difference(setb)) 输出:{10, 20} print(seta-setb) 输出:{10, 20} print(seta.symmetric_difference(setb)) 输出:{10, 50, 20, 30} print(seta^setb) 输出:{10, 50, 20, 30} print(seta.copy()) 输出:{40, 10, 20} print(seta.copy() is seta) 输出:False
集合是可变的,不能作为字典中的键。而集合本身只能包含不可变,所以集合不能包含其他集合,如下这样是错误的,
[code]Traceback (most recent call last): File "D:/work/Python/StandardLibrary4.py", line 40, in <module> print(a.add(b)) TypeError: unhashable type: 'set'
工程文件下载:https://download.csdn.net/download/yysyangyangyangshan/10838713
阅读更多相关文章推荐
- 少说话多写代码之Python学习061——标准模块(time模块)
- 少说话多写代码之Python学习065——标准模块(re模块)
- 少说话多写代码之Python学习064——标准模块(正则表达式)
- 少说话多写代码之Python学习063——标准模块(shelve模块)
- 少说话多写代码之Python学习062——标准模块(random模块)
- 少说话多写代码之Python学习059——标准模块(堆)
- 少说话多写代码之Python学习060——标准模块(双端队列)
- 少说话多写代码之Python学习001——刚开始随便叨叨
- 少说话多写代码之Python学习008——字符串的方法02
- 少说话多写代码之Python学习008——字符串的方法02
- 少说话多写代码之Python学习002——环境搭建
- Python基础学习代码之映像集合
- 机器学习实战python版第三章决策树代码理解
- python爬虫学习(下)——爬虫代码实现
- python之集合学习笔记
- 人人都能用Python写出LSTM-RNN的代码![你的神经网络学习最佳起步]
- 【代码学习】PYTHON 私有化
- Python中集合的内建函数和内建方法学习教程
- Python 学习笔记 -- 变量、元组、列表、字典和集合
- Python学习pygal绘制线图代码分享