内容简介:来看看集合(set)的使用。集合类set在sets模块中,Python2.3之后,集合类已经成为语言的一部分,无需再导入sets模块。先看看简单的使用,集合中重复值是被忽略的,比如这样,
来看看集合(set)的使用。集合类set在sets模块中,Python2.3之后,集合类已经成为语言的一部分,无需再导入sets模块。
先看看简单的使用,
print(set(range(10)))
输出
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
集合中重复值是被忽略的,比如这样,
single=set([1,6,7,8,6,6,6,8])
print(single)
输出
{8, 1, 6, 7}
元素的顺序,不会依照声明时的顺序,
sort = set(['陆小凤','西门吹雪','叶孤城'])
print(sort)
输出
{'叶孤城', '西门吹雪', '陆小凤'}
集合可以做一些运算,定义了集合seta和setb,做如下运算,
比如并集
seta=set([10,20,40])
setb=set([30,40,50])
setc = seta.union(setb)
print(setc)
输出
{50, 20, 40, 10, 30}
按位与,
print(seta |setb)
输出
{50, 20, 40, 10, 30}
其他一些运算,
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
集合是可变的,不能作为字典中的键。而集合本身只能包含不可变,所以集合不能包含其他集合,如下这样是错误的,
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 数据分析指北之 KNIME 模块:Data Access 类型模块之二 Database 模块集合
- Scala 中的集合(二):集合性能比较
- Scala 中的集合(二):集合性能比较
- 《面试知识,工作可待:集合篇》:Java 集合面试知识大全
- 如何对集合对象求合计,然后追加在该集合对象中
- MongoDB指南---14、特殊的索引和集合:固定集合、TTL索引、全文本索引
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Distributed Algorithms: An Intuitive Approach
Wan Fokkink / MIT Press / 2018-2-2 / USD 48.00
The new edition of a guide to distributed algorithms that emphasizes examples and exercises rather than the intricacies of mathematical models. This book offers students and researchers a guide to ......一起来看看 《Distributed Algorithms: An Intuitive Approach》 这本书的介绍吧!