集合定义格式
基本语法:
#定义集合字面量
{元素,元素,元素......,元素}
#定义集合变量
变量名称={元素,元素,元素......,元素}
#定义空集合
变量名称=set()
python
#定义集合字面量 {元素,元素,元素......,元素}
{1,2,7,"zhangsan"}
#定义集合变量 变量名称={元素,元素,元素......,元素}
name={3,"zhangsan",5,"lisi"}
print(f"name的类型是{type(name)},name的内容:{name}")
#定义空集合 变量名称=set()
j=set()
print(f"j的类型是{type(j)},内容为:{j}")
集合的常用操作
集合是无序的,所以集合不支持:下标索引访问,
但集合和列表一样允许修改
添加新元素
集合本身被修改,添加新元素
语法:集合.add(元素)
python
name.add("python")
print(f"name的类型是{type(name)},name的内容:{name}")
name.add("python")
print(f"name的类型是{type(name)},name的内容:{name}")
集合不允许重复,所以只添加一次"python"
移除元素
语法:集合.pop() 从集合中随机取出元素
结果:会得到一个元素的结果。同时集合本身被修改,元素被移除
python
#移除元素
my_set={3,"zhangsan",5,"lisi","lisi","wangwu"}
element=my_set.pop()
print(my_set)
print(element)
清空集合
语法:集合.clear() 清空集合
结果:集合被清空
python
#清空集合
print(name)
name.clear()
print(name)
取两个集合的差集
语法:集合1.difference(集合2) 取出集合1和集合2的差集(集合1有,集合2没有的)
结果:得到一个新集合,集合1和集合2不变
python
#取两集合差集
my_set1={3,"zhangsan",5,"lisi","lisi","wangwu","c++"}
my_set2={"java","python","php","zhangsan",6}
my_set3=my_set2.difference(my_set1)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
print(f"my_set3的内容是{my_set3}")
消除2个集合的差集
语法:集合1.diference_update(集合2)
功能:对比集合1和集合2,在集合1内,删除和集合2相同的元素
结果:集合1被修改,集合2不变
python
#消除两集合差集
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
my_set1.difference_update(my_set2)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
合并集合
语法:集合1.union(集合2)
结果:得到新集合,集合1和集合2不变
python
#合并集合
my_set1={3,"zhangsan",5,"lisi","lisi","wangwu","c++"}
my_set2={"java","python","php","zhangsan",6}
my_set3=my_set2.union(my_set1)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
print(f"my_set3的内容是{my_set3}")
统计集合元素数量
语法:len(集合)
注意:集合会去重
集合的遍历
集合不支持下标索引,所以不能用while循环
可以用for循环
python
#定义集合字面量 {元素,元素,元素......,元素}
{1,2,7,"zhangsan"}
#定义集合变量 变量名称={元素,元素,元素......,元素}
name={3,"zhangsan",5,"lisi"}
print(f"name的类型是{type(name)},name的内容:{name}")
#定义空集合 变量名称=set()
j=set()
print(f"j的类型是{type(j)},内容为:{j}")
#添加元素
name.add("python")
print(f"name的类型是{type(name)},name的内容:{name}")
name.add("python")
print(f"name的类型是{type(name)},name的内容:{name}")
#移除元素
my_set={3,"zhangsan",5,"lisi","lisi","wangwu"}
element=my_set.pop()
print(my_set)
print(element)
#清空集合
print(name)
name.clear()
print(name)
#取两集合差集
my_set1={3,"zhangsan",5,"lisi","lisi","wangwu","c++"}
my_set2={"java","python","php","zhangsan",6}
my_set3=my_set2.difference(my_set1)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
print(f"my_set3的内容是{my_set3}")
#消除两集合差集
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
my_set1.difference_update(my_set2)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
#合并集合
my_set1={3,"zhangsan",5,"lisi","lisi","wangwu","c++"}
my_set2={"java","python","php","zhangsan",6}
my_set3=my_set2.union(my_set1)
print(f"my_set1的内容是{my_set1}")
print(f"my_set2的内容是{my_set2}")
print(f"my_set3的内容是{my_set3}")
#遍历元素
for i in my_set1:
print(i)