set集合
1、 创建集合并去重
方法一 : {}
one_set = set([10,30,10,20,40,11,20,30,12]) print(one_set) print(type(one_set))
结果:
方法二:set([ ])
one_set = set([10,30,10,20,40,11,20,30,12])
print(one_set)
print(type(one_set))
结果:
2、 创建空集合
不能使用 {} 来创建空集合,默认创建的是空字典
使用set:
empty_set = set()
print(empty_set)
print(type(empty_set))
结果:
3、 求交集
方法一: &
one_set ={10,30,10,20,40,11,20,30,12}
two_set ={10,30,60,90,80,76}
result_set1 = one_set & two_set
print(result_set1)
结果:
方法二: one_set.intersection(two_set)
one_set ={10,30,10,20,40,11,20,30,12}
two_set ={10,30,60,90,80,76}
result_set11 = one_set.intersection(two_set)
print(result_set11)
结果:
4、 求并集
方法一 |
one_set ={10,30,10,20,40,11,20,30,12}
two_set ={10,30,60,90,80,76}
result_set2 = one_set | two_set
print(result_set2)
结果:
方法二: one_set.union(two_set)
one_set ={10,30,10,20,40,11,20,30,12}
two_set ={10,30,60,90,80,76}
result_set22 = one_set.union(two_set)
print(result_set22)
结果:
5、 求差集
方法一 : -
one_set ={10,30,10,20,40,11,20,30,12} two_set ={10,30,60,90,80,76} result3 = one_set - two_set print(result3)
结果:
方法二:
one_set ={10,30,10,20,40,11,20,30,12}
two_set ={10,30,60,90,80,76}
result33 = one_set.difference(two_set)
print(result33)
结果: