一、集合
1.1 集合的特征
集合是无序的,集合中的元素是唯一的,集合一般用于元组或者列表中的元素去重
1.2 集合的格式
格式
变量名=set()
变量名.add(元素)
#必须不能初始化或变量名={元素,元素,,,}
注意:下面写法为一个空字典,为空默认是字典,如果有数据在根据格式判断为字典还是集合
1.3 添加元素
1.3.1 add
nums = {11,24,45,96,28}
nums.add(42)
print(nums)
#{96, 42, 11, 45, 24, 28}
1.3.2 update
nums = {11,24,45,96,28}
nums2=[“anfly”,“tom”]
nums.update(nums2)
print(nums)
#{96, ‘anfly’, 11, 45, 24, 28, ‘tom’}
1.4:删除元素
remove,pop,discard
1.4.1 remove
使用remove删除集合中的元素 如果有直接删除 如果没有程序报错
案例:该元素存在
nums = {11,24,45,96,28}
nums.remove(24)
print(nums)
#{96, 11, 45, 28}
案例:该元素不存在
nums = {11,24,45,96,28}
nums.remove(245)
print(nums)
#KeyError: 245
1.4.2 pop
1、如果集合的元素都是数字, 删除时, 删掉的是最小的数字, 其余数字升序排列
2、如果