Python之集合操作
set 集合
set是 可变的、 无序的、不重复 的元素的集合
set的定义初始化
set() -> new empty set object
set(iterable) -> new set object
1 | s1 = set() |
set() {0, 1, 2, 3, 4} {0, 1, 2, 3, 4} {1, 2, 3, 4} {1, 2, 3, 4}
但是:
- set的元素要求必须可以hash
- 目前学过的不可hash的类型有list、 set,所以set不能添加list或set
- 元素不可以使用索引
- set可以迭代
1 | s1 = { [1,2],3,4 } |
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-562af6839204> in <module>
----> 1 s1 = { [1,2],3,4 }
2 s2 = { {1,2},3,4 }
TypeError: unhashable type: 'list'
set增加
add(elem)
增加一个元素到set中
如果元素存在,什么都不做
1 | s1 = {1,2,3,4,5} |
{1, 2, 3, 4, 5, 6}
update(*others)
合并其他元素到set集合中来
参数others必须是可迭代对象
就地修改
1 | s1 = {1,2} |
{0, 1, 2, 3, 4, 'a', 'b'}
set 删除
remove(elem)
从set中移除一个元素
元素不存在,抛出keyerror异常
1 | s1 = {1,2,3,4} |
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-5-06ea004ed743> in <module>
1 s1 = {1,2,3,4}
2 s1.remove(1)
----> 3 s1.remove(1)
KeyError: 1
discard(elem)
从set中移除一个元素
元素不存在,什么都不做
1 | s1 = {1,2,3,4} |
{2, 3, 4}
pop() -> item
移除并返回任意的元素
空集返回KeyError异常
1 | s1 = {1,2} |
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-7-cb8a0766400b> in <module>
2 s1.pop()
3 s1.pop()
----> 4 s1.pop()
KeyError: 'pop from an empty set'
clear()
移除所有元素
1 | s1 = {1,2,3} |
set()
set的修改、查询
修改
set中没有修改的说法,修改删除元素,然后添加新元素
查询
set是非线性结构,无法通过索引来查询元素
遍历
set可以迭代通过for循环所有元素
1 | s1 = {1,2,3,4} |
1
2
3
4
成员运算符
set是通过in 或者 not in 判断元素是否在set中
线性结构和非线性结构的差别
线性结构的查询时间复杂度是O(n),即随着数据规模的增大而增加耗时
set、 dict等结构,内部使用hash值作为key,时间复杂度可以做到O(1),查询时间和数据规模无关
可hash数据类型
数值型int、 float、 complex
布尔型True、 False
字符串string、 bytes
tuple
None
以上都是不可变类型,是可哈希类型, hashable
set的元素必须是可hash的