集合
集合(set)的特点
- 无序性(用{}都没有索引)
- 互异性
- 确定性——集合中的元素不能有可变对象,如列表、字典
如何创建集合
- 可变集合
- 不可变集合
s = {1, 2, 3}
type(s)
<class 'set'>
s2 = {2, 1, 3}
s == s2
True
s= {1,2,2,3}
s
{1, 2, 3} #互异性
lst = [1, 2, 2, 3, 3, 4, 4, 5]
set(lst)
{1, 2, 3, 4, 5}
fs = frozenset({1, 2, 3})
fs
frozenset({1, 2, 3}) # 不可变集合
集合的方法
增加元素的方法
- add
- update
s.add(99)
s
{99, 1, 2, 3}
s.update(set({'hello', 'python'}))
s
{1, 2, 99, 3, 'hello', 'python'}
删除元素
- pop
- remove
- discard——就集合中没有该元素,也不会报错
- clear
s.pop()
1
s.pop()
2
s.remove('hello')
s
{99, 3, 'python'}
s.discard(3)
s
{99, 'python'}
s.remove(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 3
s.discard(3)
集合的关系和运算
- 元素和集合的关系
- 集合与集合的关系
- 集合间的运算
- 并集
- 交集
- 差集
a = set([1, 2, 3, 4, 5, 6])
b = set([1, 2, 3])
a.issuperset(b) #a是否为b的超集
True
b.issubset(a) #b是否为a的子集
True
a.union(b)
{1, 2, 3, 4, 5, 6}
a | b
{1, 2, 3, 4, 5, 6}
并集
a.intersection(b)
{1, 2, 3}
a & b
{1, 2, 3}
交集
a.difference(b)
{4, 5, 6}
a - b
{4, 5, 6}
b - a
set()
差集
浅拷贝和深拷贝
- 容器:列表、元组、字典、(可变)集合
- 列表、字典、集合:
- 浅拷贝:只拷贝最外层
- 深拷贝:import copy
浅拷贝
lst = [1, 2, 3]
lst2 = lst.copy()
id(lst)
1653129624576
id(lst2)
1653129624512
lst = [[1, 2, 3]]
lst2 = lst.copy()
id(lst[0])
1653129625088
id(lst2[0])
1653129625088
lst[0].append(888)
lst2
[[1, 2, 3, 888]]
深拷贝
import copy
lst
[[1, 2, 3, 888]]
dlst = copy.deepcopy(lst)
dlst
[[1, 2, 3, 888]]
id(lst[0])
1653129625088
id(dlst[0])
1653129698240
网友评论