集合
# 定义集合
num = {1, 2, 3, 4, 5}
print(f"num:{num}\nnum数据类型为:{type(num)}")
# 求集合中元素个数
print(f"num中元素个数为:{len(num)}")
# 增加集合中的元素
num.add(6)
print(num) # {1,2,3,4,5,6}
# 删除集合中的元素
num.remove(4)
print(num) # {1,2,3,4,6}
# 从集合中移除并返回任意一共元素,会影响原来的集合
a = num.pop()
print(f"a:{a},num:{num}")
# union (|)两个集求并集 name1 = {"bob", "jack", "tonnny", "amy"} name2 = {"bob", "tom", "rose", "jack"} name_a = name1.union(name2) name_b = name2 | name1 print(name_a, "\n", name_b)# intersection(&)求两个集合的交集 name = name1.intersection(name2) nam = name1 & name2 print(f"name:{name},nam:{nam}")# 求一个集合在另一个集合中的补集 n=name1.difference(name2) #{"tonnny","amy"} m=name2.difference(name1) #{"tom", "rose"} print(f"n:{n}\nm:{m}")# {集合的表达式 for 自变量 可迭代对象} set={i for i in range(1,5)} print(set)
Chinese={"小张","小王","小李","小刘","jack"} Math={"小张","bob","rose","小刘","jack"} English={"小张","tom","tony","amy"}# 选课学生总人数-集合的并集All_num All_num=Chinese|Math|English print(f"选课学生总人数:{len(All_num)}人,分别为{All_num}")#只选了Chinses的学生人数和姓名 Only_name=Chinese-Math-English print(f"只选了Chinses的学生人数:{len(Only_name)}/学生姓名{Only_name}")#只选择一门课的学生人数 # 只选语文 One_name1=Chinese-Math-English # 只选数学 One_name2=Math-English-Chinese #只选英语 One_name3=English-Chinese-Math # 求并集 One_name=One_name1|One_name2|One_name3 print(f"只选择一门课的学生人:{One_name},总人数为{len(One_name)}")#三门课都选的学生,求交集 ALL=Chinese&Math&English print(f"三门课都选的学生:{ALL},总人数为{len(ALL)}")