这篇文章主要记录自己学习Python中的set集合类型
首先,set集合有个特点就是,set集合是可变的,但里面的元素是不重复,无序的!!!
set定义 初始化
- set() -> new empty set object
- set(iterable) -> new set object
>>> s = set(range(5))
>>> s
{0, 1, 2, 3, 4}
>>> s6 = {(1,2),3,'a'}
>>> s6
{(1, 2), 3, 'a'}
set的元素
- set的元素要求必须可以hash
>>> s = {[1],(1,),1}
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
s = {[1],(1,),1}
TypeError: unhashable type: 'list'
这里报错的原因是因为,set里面的元素 [1] ,是列表,是不可哈希的元素,不可hash的类型有list、set
- 元素不可以索引
- set可以迭代
set增加
- add(elem):
1.增加一个元素到set中
2.如果元素存在