python学习Day8-集合
集合(set)一般帮列表去重
去重
tang = [123,123,456,789]
tang = set(tang)
tang
{123, 456, 789}
结构
tang = set()
type(tang)
set
集合的操作
并(union或 | )
a = {1,2,3,4,5,6}
b = {3,4,5,6,7,8}
a.union(b)
{1, 2, 3, 4, 5, 6, 7, 8}
b.union(a)
{1, 2, 3, 4, 5, 6, 7, 8}
a|b
{1, 2, 3, 4, 5, 6, 7, 8}
交(intersection或 & )
a.intersection(b)
{3, 4, 5, 6}
b.intersection(a)
{3, 4, 5, 6}
a & b
{3, 4, 5, 6}
差(difference或 - )
a.difference(b)
{1, 2}
b.difference(a)
{7, 8}
a - b
{1, 2}
b - a
{7, 8}
判断包含关系(issubset或<=、>)
a = {1,2,3,4,5,6}
b = {2,3,4}
b.issubset(a)
True
b <= a
True
a.issubset(b)
False
b > a
False
添加元素(add)
a = {1,2,3}
a.add(4)
a
{1, 2, 3, 4}
更新(update)
a.update([2,3,4,5])
a
{1, 2, 3, 4, 5}
删除元素(remove)
a.remove(2)
a
{1, 3, 4, 5}
弹出元素(pop)与列表和字典不同
- 不能用下标弹出,只能从第一个依次弹出
a.pop()
1
a.pop()
3
未完待续