
上QQ阅读APP看书,第一时间看更新
5.4 集合
上一节介绍了Python中的字典,Python中的字典是对数学中映射概念支持的直接体现。接下来将讲解一个和字典非常相似的对象:集合。
示例如下:
>>> student={} >>> print(f'student对象的类型为:{type(student)}') student对象的类型为:<class 'dict'> >>> number={1,2,3} >>> print(f'number对象的类型为:{type(number)}') number对象的类型为:<class 'set'>
由输出结果可以看到,这里出现了一个新的类型set。
在Python中,用花括号括起一些元素,元素之间直接用逗号分隔,这就是集合。集合在Python中的特性可以概括为两个字:唯一。
示例如下:
>>> numbers={1,2,3,4,5,3,2,1,6} >>> numbers {1, 2, 3, 4, 5, 6}
由输出结果可以看到,set集合中输出的结果自动将重复数据清除了。
需要注意的是,集合是无序的,不能通过索引下标的方式从集合中取得某个元素。例如:
>>> numbers={1,2,3,4,5} >>> numbers[2] Traceback (most recent call last): File "<pyshell#143>", line 1, in <module> numbers[2] TypeError: 'set' object does not support indexing
由输出结果可以看到,在集合中使用索引下标时,执行报错,错误提示为:集合对象不支持索引。