python 資料型別set集合
阿新 • • 發佈:2021-02-05
python 資料型別set集合
- 1、集合的特性
- 2、集合之間的邏輯關係
- 3、集合常用的方法
- 3.1、add() 向集合中新增元素
- 3.2、clear() 清空集合
- 3.3、copy() 複製集合
- 3.4、discard() 刪除集合中指定的元素,該元素不存在不會報錯
- 3.5、remove() 刪除集合中指定的元素,該元素不存在報錯
- 3.6、pop() 隨機刪除集合中一個元素
- 3.7、update() 更新集合,把‘引數’新增到集合中
- 3.8、union() 並集,返回這個並集
- 3.9、intersection() 求交集 ,返回這個交集
- 3.10、difference() 求差集,返回呼叫difference()方法的集合差集
- 3.11、difference_update() 求差集,還會刪除交集的部分
- 3.12、intersection_update() 求交集,還會刪除差集的部分
- 3.13、symmetric_difference() 求差集,返回所有集合不相同的
- 3.14、symmetric_difference() 求差集,把y中x沒有的,都新增到x中
- 3.15、isdisjoint() 判斷兩個集合是否包含相同的元素,如果沒有返回 True,否則返回 False。
- 3.16、issubset() 判斷指定集合是否為該方法引數集合的子集。
- 3.17、issuperset() 判斷該方法的引數集合是否為指定集合的子集
1、集合的特性
1、集合中的元素是獨一無二
2、集合不能用 連線符“+” 連線兩個集合
3、集合是可變型別
4、集合是無序的,所以不能切片
5、空集合用set()定義,不能用{},{}定義的是空字典
2、集合之間的邏輯關係
2.1、並集
2.2、交集
2.3、差集
3、集合常用的方法
3.1、add() 向集合中新增元素
x = {1,2,3,4,5}
x.add('a')
print(x) # {1, 2, 3, 4, 5, 'a'}
3.2、clear() 清空集合
x = {1,2,3,4, 5}
x.clear()
print(x) # set()
3.3、copy() 複製集合
x = {1, 2, 3, 4, 5}
a = x.copy()
print(a) # {1, 2, 3, 4, 5}
3.4、discard() 刪除集合中指定的元素,該元素不存在不會報錯
x = {1, 2, 3, 4, 5}
x.discard(3)
x.discard(8) # 被刪除的物件不再集合中也不會報錯
print(x)
3.5、remove() 刪除集合中指定的元素,該元素不存在報錯
x = {1, 2, 3, 4, 5}
x.remove(2)
print(x) #{1, 3, 4, 5}
x.remove(8) # 刪除的元素,集合中不存在,報錯KeyError: 8
# Traceback (most recent call last):
# File "D:/manager_project/ShoppingMall/test_study.py", line 84, in <module>
# x.remove(8)
# KeyError: 8
3.6、pop() 隨機刪除集合中一個元素
x = {1, 2, 3, 4, 5}
x.pop()
print(x) # {2, 3, 4, 5}
3.7、update() 更新集合,把‘引數’新增到集合中
注意:update( **iter ) 引數必須是迭代物件
x = {1, 2, 3, 4, 5}
x.update({'a','b','c'})
x.update(('v','vv'))
print(x) # {1, 2, 3, 4, 5, 'b', 'v', 'vv', 'c', 'a'}
3.8、union() 並集,返回這個並集
x = {1,2,3,4,5}
y = {1,2,6,7,8}
z = x.union(y) # 求集合x與集合y的並集,並返回一個新集合
print(z) #{1, 2, 3, 4, 5, 6, 7, 8}
3.9、intersection() 求交集 ,返回這個交集
x = {1,2,3,4,5}
y = {1,2,6,7,8}
z = x.intersection(y)
print(z) # {1, 2}
3.10、difference() 求差集,返回呼叫difference()方法的集合差集
x = {1,2,3,4,5}
y = {1,2,6,7,8}
z = x.difference(y) # 求集合x與集合y的差集,返回集合x中集合y沒有的元素
print(z) # {3, 4, 5}
3.11、difference_update() 求差集,還會刪除交集的部分
x = {1,2,3,4,5}
y = {1,2,6,7,8}
x.difference_update(y)
print(x) # {3, 4, 5}
3.12、intersection_update() 求交集,還會刪除差集的部分
x = {1,2,3,4,5}
y = {1,2,6,7,8}
x.intersection_update(y)
print(x) # {1, 2}
3.13、symmetric_difference() 求差集,返回所有集合不相同的
x = {1,2,3,4,5}
y = {1,2,6,7,8}
z = set.symmetric_difference(x,y)
print(z) # {3, 4, 5, 6, 7, 8}
3.14、symmetric_difference() 求差集,把y中x沒有的,都新增到x中
x = {1,2,3,4,5}
y = {1,2,6,7,8}
x.symmetric_difference_update(y)
print(x) # {3, 4, 5, 6, 7, 8}