集合的定义方式
定义一个空集合 s = set ()
包含一个元素集合 s = {"hello"}
定义多个元素集合 s = {"python","java"}
注意:set中元素不可重复,类似dict中的键,且无序,集合里面不能包含list
集合增、删、查
增:set(add)
- 题目1:set1 = {"python",java } # 则需要增加一个php
set1.add ("php") # 注意增加的位置随机的
- 题目2:set1 = {"python","java"}
set2 = {"jenkins","mysql"}
则需要把set2放到set1里面去
set1.update(set2)输出结果set1就包含set2
删:
- 题目3:set1 = {"python",java } 则删除其中一个元素
set1.pop() # 注意:删除集合中的任意一个元素可能是python也可能是java
set1.remove("java") # 注意:remove删除的是指定元素
set1.discar("python") # 注意:discar删除如果里面有或无"Python"均不会报错,但是remove就会报错
查:
- 题目4:set1 = {"python",java }
len(set1) # 统计集合里面元素个数
其他:
set1.clear() # 清空集合里面内容
- 题目5:set1 = {"python",java }
set2 = set1.copy() # 复制集合这这时候set2也等于{python,java}
六种集合的方法:
交集:&
- 题目6:code = {"python",java }
code1 = {"python","php","java"}
code & code1 也可以code.intersection(code1),code&code1 # 则输出结果就是python,java,php
并集:|
- 题目7:code = {"python","java","js" }
code1 = {"python","php","java"}
code | cpde1 也可以code.union(code1),code|code1 # 则输出结果就是python,java,php,js
差集:-
- 题目8:code = {"python","java","js" }
code1 = {"python","php","java"}
code - code1 也可以code.difference,code-code1 # 则输出结果就是js,php
对称差集:^
- 题目9:code = {"python","java","js" }
code1 = {"python","php","java"}
code ^ code1 也可以写成code.symmetric_difference # 则输出就是js,php (意思就是输出code,code1两个不一样的元素)
子集:<=
- 题目10:code = {"python","java",20,30 }
code1 = {"python"}
code1 <= code 也可以写成code1.issubset(code) # 则输出就是True(意思是code1是code元素里面的一个子集)
包含:>=
- 题目11:code = {"python","java",20,30 }
code1 = {"python"}
code >= code1 也可以写成code.issuperset(code1) # 则输出就是True(意思是code包含code1元素)
四种集合赋值方法:
交集并赋值: &=
- 题目12:set1 = {"php","java",2018}
set2 = {"java","2019","python"}
set1 &= set2 也可以写成set1.intersection_update(set2) # 则输出就是python(注意这时候set1赋值后是python,而不是php,java,2018)
并集并赋值: |=
- 题目13:set1 = {"php","java",2018}
set2 = {"java","2019","python"}
set1 |= set2 也可以写成set1.update(set2) # 则输出结果就是python,java,php,2019,2018
差集并赋值: -=
- 题目14:set1 = {"php","java",2018}
set2 = {"java","2019","python"}
set1 -= set2 也可以写成set1.difference_update(set2) # 则输出结果就是2018,php
对称集并赋值:^=
- 题目15:set1 = {"php","java",2018}
set2 = {"java","2019","python"}
set1^= set2 也可以写成set1.symmetrin_update # 则输出结果是2018,2019,php,java (对称集就是去除所重复的数据)