集合(set):
特性:
1.集合的元素都是唯一的。
2.集合是无序的(非线性序列)。
set的定义(初始化):
s = set()
s = {1, 2, 3}
增加元素:添加的元素必须是可hash的,list、set、bytearray、dict是不可hash的,所以不能作为set的元素,通常来说内置类型不能变的都是可hash的。
add方法:添加一个元素到集合,如果该元素在集合已经存在,集合不会发生任何改变(集合的元素都是唯一的)。
add(...)
Add an element to a set.
This has no effect if the element is already present.
>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(2)
>>> s
{1, 2, 3, 4}
update方法:将一个可迭代对象更新到集合。
update(...)
Update a set with the union of itself and others.
>>> s
{1, 2, 3, 4}
>>> s.update({4, 5, 6})
>>> s
{1, 2, 3, 4, 5, 6}
>>> s.update([1, 22 ,11])
>>> s
{1, 2, 3, 4, 5, 6, 22, 11}
>>> s.update('python')
>>> s
{1, 2, 3, 4, 5, 6, 11, 22, 'h', 'n', 'y', 'p', 'o', 't'}
>>> s.update({'a':1, 'b':2})
>>> s
{1, 2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'} #update字典时只会添加字典的key到集合。
>>>
删除元素:
remove方法:删除集合的一个元素,如果该元素不存在,则抛出一个KeyError异常。
remove(...)
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
>>> s
{1, 2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}
>>> s.remove(1)
>>> s
{2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}
>>> s.remove(100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100
>>>
discard方法:删除集合的一个元素,如果该元素不存在,则什么都不做。
discard(...)
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
>>> s
{2, 3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}
>>> s.discard(2)
>>> s
{3, 4, 5, 6, 'b', 11, 22, 'a', 'h', 'n', 'y', 'p', 'o', 't'}
>>> s.discard(200)
>>>
pop方法:随机删除集合的一个元素,并返回该元素,如果集合为空则抛出一个KeyError异常。
pop(...)
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
>>> s
{1, 2, 3}
>>> s.pop()
1
>>> s.pop()
2
>>> s.pop()
3
>>> s.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop from an empty set'
>>>
clear方法:删除集合的所有元素。
clear(...)
Remove all elements from this set.
>>> s
{1, 2, 3}
>>> s.clear()
>>> s
set()
>>>
修改元素和查找元素:
没有任何方法可以直接修改和查找集合中的某个具体元素,因为集合是无序的,所以没有任何方法能够定位到集合某个元素的位置。
访问方法:
集合是可迭代对象,可以使用成员运算符(in、 not in)
可以使用for in的方式访问集合
线性结构的成员运算,时间复杂度是O(n),集合的成员运算,时间复杂度是O(1)
额外拓展:时间复杂度
效率排列:
O(1) 常数复杂度
O(logn) 对数复杂度
O(n) 线性复杂度
O(n^2) 平方复杂度
O(n^3)
O(2^n) 指数复杂度
O(n!) 阶乘复杂度