一、集合的相关定义
1、集合set,可迭代对象
由不同的元素组成,无序排列、不可变数据类型。由大括号{},以逗号分隔方式定义
2、集合的内置方法
普通集合属于可变数据类型,如果属性为:l_s=frozenset(linux_1)就为不可变的数据类型
2.1 add添加元素,只能存放一个元素
2.2 clear清空元素
2.3 copy浅拷贝
2.4 pop随机删除元素
2.5 remove("s")删除指定元素,且删除不存在的元素会报错
2.6 discord("sfr")删除指定元素,且删除不存在元素时不报错
2.7 difference_update,两个集合不同元素,且更新集合中的元素
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) p_s.difference_update((l_s)) print(p_s) 结果: {222, 'nana'}
2.8 isdisjoint,两个集合之间不存在交集时,返回Frue,否则False
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.isdisjoint((l_s))) False
2.9 issubset,判断是否是包含关系,子集关系
python_1=["baby","123"] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.issubset((l_s))) #p_s是否是l_s的子集 结果: True
2.10 issuperset,判断是否是包含关系,父集关系
python_1=["baby","123"] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.issuperset((l_s))) #p_s是否是l_s的父集 False
2.11update更新指定的集合中的元素,可以同时更新多个值(元组、列表)
python_1=["baby","123"] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) p_s.update(l_s) p_s.update((3,4,"444")) print(p_s)
3、集合关系
3.1交集
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.intersection(l_s)) print(p_s&l_s) 结果: {'baby', '123'}
3.2并集,不更新集合本身的数据
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.union(l_s)) print(p_s|l_s) 结果: {'baby', '娜娜', '中华', 'nana', 999, '123', 222}
3.3差集
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.difference(l_s)) print(p_s-l_s) 结果: {'nana', 222}
3.4交叉补集
python_1=["nana","baby","123",222] linux_1=["娜娜","baby","123",999,"中华"] p_s=set(python_1) l_s=set(linux_1) print(p_s.symmetric_difference(l_s)) print(p_s^l_s) 结果: {'娜娜', 999, 'nana', '中华', 222}