集合set
1.由不同元素组成的集合,集合是一组无序排列的,集合中的元素必须是不可变的
-定义集合
第一种:
jh = {1,2,3,4} print(type(jh),jh)
运行结果:
<class 'set'> {1, 2, 3, 4} Process finished with exit code 0
第二种:
jh = set('hello') print(type(jh),jh)
运行结果:
<class 'set'> {'e', 'o', 'h', 'l'} Process finished with exit code 0
-添加元素
jh = {1,2,3,4} jh.add("nihao") print(jh)
{1, 2, 3, 4, 'nihao'} Process finished with exit code 0
-删除
*.clear 清除集合
*.pop 随机删除
jh = {1,2,3,4} jh.pop() print(jh)
运行结果:
{2, 3, 4}
Process finished with exit code 0
*.remove 删除指定元素(如果指定的元素不在,会报错)
jh = {1,2,3,4} jh.remove(4) print(jh)
运行结果:
{1, 2, 3}
Process finished with exit code 0
*.discard 删除指定元素(如果指定元素不在,不会报错)
-交集 &
math = {'xm','xh','xg'} english ={'xm','xh'} print(math.intersection(english))
运行结果:
{'xh', 'xm'} Process finished with exit code 0
-并集 |
math = {'xm','xh','xg','xx'} english ={'xm','xh','dm','john'} print(math.union(english))
运行结果:
{'xg', 'dm', 'john', 'xm', 'xx', 'xh'} Process finished with exit code 0
-差集(也可以两个集合做减法)
math = {'xm','xh','xg','xx'} english ={'xm','xh','dm','john'} print(math.difference(english)) print(english.difference(math))
运行结果:
{'xg', 'xx'} {'dm', 'john'} Process finished with exit code 0