python 集合定义和基本操作方法 day14
集合
1不同元素组成
2无序
3集合中元素必须是不可变类型
不可变:字符串、数字、元组
可变:列表、字典
创建集合
{1,2,3,4}
或定义可变集合set)
s = set('hello') print (s) s = set(['alex','alex','sb']) print (s)
添加进集合
add 已有元素add添加可运行,不显示
s={1,2,3,4,5,6} s.add(7) print(s)
clear 清空集合
s={1,2,3,4,5,6} s.clear() print(s)
copy 复制集合
s={1,2,3,4,5,6} s1 = s.copy() print(s) print(s1)
pop 删除一个元素,随机删除
s={'sss',1,2,3,4,5,6} s.pop() print(s)
remove 删除一个特定元素,删除不存在会报错
s={'sss',1,2,3,4,5,6} s.remove(1) print(s)
discard 删除一个特定元素,删除不存在元素不报错
s={'sss',1,2,3,4,5,6} s.discard(7) print(s)
集合重用操作:关系运算
in
not in
==
!=
<.<=
>,>=