集合(set)
定义:由不同元素组成的集合,集合中是一组无序排列可hash的值(不可变的值)例如数字、字符串、元组,可以作为字典的key
定义集合:
# 定义集合 s = {1, 2, 3, 3, 3, 4, 5} print(s) print(type(s))
输出:
{1, 2, 3, 4, 5} <class 'set'>
定义可变集合set
# 定义可变集合 s = set("hello") # ()内为可迭代类型 print(s)
输出:
{'l', 'h', 'o', 'e'}
定义不可变集合
# 定义不可变集合 s = frozenset("hello") # ()内为可迭代类型 print(s)
输出:
frozenset({'l', 'h', 'e', 'o'})
集合关系运算(方法)
1、intersection()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求交集 print(num1.intersection(num2)) # 相当于 print(num1 & num2)
输出:
{2, 3} {2, 3}
2、union()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求并集 print(num1.union(num2)) # 相当于 print(num1 | num2
输出:
{1, 2, 3, 4} {1, 2, 3, 4}
3、difference()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求差集 print(num1.difference(num2)) # 输出num1中有num2中没有的 # 相当于 print(num1 - num2)
输出:
{1} {1}
4、symmetric_difference()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求交差补集 print(num1.symmetric_difference(num2)) # 并集合交集的差集 # 相当于 print(num1 ^ num2)
输出:
{1, 4} {1, 4}
方法
1、add()
s = {1, 2, 3, 4} # 添加一个元素 s.add((1, 2)) s.add(1) print(s)
输出:
{(1, 2), 1, 2, 3, 4}
2、clear()
3、copy()
4、pop()(随机删除)
s = {1, 2, 3, 4, "Aiden", 5, 6, 7, 8} # 随机删除 s.pop() print(s)
输出:
{1, 2, 3, 4, 5, 6, 7, 8}
5、remove()
s = {1, 2, 3, 4, "Aiden", 5, 6, 7, 8} # 指定元素删除 s.remove(3) # 指定的元素不存在会报错 print(s)
输出:
{'Aiden', 1, 2, 4, 5, 6, 7, 8}
6、discard()
s = {1, 2, 3, 4, "Aiden", 5, 6, 7, 8} # 指定元素删除 s.discard(3) # 指定的元素不存在不会报错 print(s) s.discard(12) print(s)
输出:
{1, 2, 4, 5, 6, 7, 8, 'Aiden'}
7、difference_update()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求完num1和num2的差集后自动复制给num1 num1.difference_update(num2) print(num1)
输出:
{1}
8、intersection_update()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求完num1和num2的交集后自动复制给num1 num1.intersection_update(num2) print(num1)
输出:
{2, 3}
9、isdisjoint()
num1 = {1, 2} num2 = {3, 4} # 判断两个集合是否互斥 print(num1.isdisjoint(num2))
输出:
True
10、issubset()
num1 = {1, 2} num2 = {1, 2, 3} # 判断num1是否为num2的子集 print(num1.issubset(num2)) # 相当于print(num1 <= num2)
输出:
True
11、issuperset()
num1 = {1, 2} num2 = {1, 2, 3} # 判断num2是否为num1的父集 print(num2.issuperset(num1)) # 相当于print(num2 >= num1)
输出:
True
12、symmetric_difference_update()
num1 = {1, 2, 3} num2 = {2, 3, 4} # 求交差补集并把结果赋给num1 num1.symmetric_difference_update(num2) print(num1)
输出:
{1, 4}
13、update()
num1 = {1, 2, 3} num2 = {2, 3, 4} # update可以更新多个值 # 相当于取并集后赋值 # num1.update(num2) # num1.update((4, 5)) num1.update([4, 5]) print(num1)
输出:
{1, 2, 3, 4, 5}
14、根据集合的特点可简单去重(无序)
来源:https://www.cnblogs.com/Fu-yi/p/11624241.html