集合的格式
变量名=set(元素,元素)
添加元素两种方法
add()---添加单个
例子
nums = {11,24,45,96,28}
nums.add(42)
print(nums)
#{96, 42, 11, 45, 24, 28}
update()------添加多个
例子
nums = {11,24,45,96,28}
nums2=["jack","tom"]
nums.update(nums2)
print(nums)
#{96, 'jack', 11, 45, 24, 28, 'tom'}
删除元素
remove-----直接删除指定元素,元素不存在时报错
例子
nums = {11,24,45,96,28}
nums.remove(24)
print(nums)
#{96, 11, 45, 28}
pop-----随机删除
例子
nums = {11,24,45,96,28}
nums.pop()
print(nums)
#{11, 45, 24, 28}
discard---直接删除指定元素,元素不存在时不报错
例子
nums = {11,24,45,96,28}
nums.discard(242)
print(nums)
#{96, 11, 45, 24, 28}
集合的交集和并集
交集
例子
set1 = {"jack","tom","haha"}
set2 = {"jack","susala"}
set3= set1 & set2
print(set3)
并集
例子
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
new_set = set1 | set2
print(new_set)
#{1, 2, 3, 4, 5, 6}