#author F
list_1 = [1, 4, 6, 8, 6, 34, 77]
list_1 = set(list_1) #列表转集合 集合和字典一样 都是无序的
print(list_1, type(list_1))
list_2 = set([4, 5, 6, 98, 2, 5])
print(list_1, list_2)
#交集
print(list_1.intersection(list_2)) #{4, 6}
#并集
print(list_1.union(list_2)) #{1, 34, 98, 4, 2, 6, 5, 8, 77}
#差集
print(list_1.difference(list_2)) #{8, 1, 34, 77} list_1里有的list_2里没有的
print(list_2.difference(list_1)) #{{98, 2, 5}} list_2里有的list_1里没有的
#子集
list_3 = set([1])
print(list_1.issubset(list_2)) #list_1是不是list_2的子集
print(list_1.issuperset(list_2)) #list_1是不是list_2的父集
print(list_1.issuperset(list_3)) #list_1是不是list_3的父集 True
#反向差集(并集去掉交集部分)
print(list_1.symmetric_difference(list_2)) #{1, 98, 2, 5, 34, 8, 77}
print("----------------------------------")
list_4 = set([3, 5])
list_5 = set([3, 4])
print(list_1.isdisjoint(list_4)) #无交集返回True
print(list_1.isdisjoint(list_5)) #有交集返回false
#集合运算符
t = set([1, 5, 9, 7, 56, 4])
s = set(["ss", 4, 5])
#交集
print(t & s)
#并集
print(t | s)
#差集
print(t - s)
#对称差集
print(t ^ s)
#集合增删改查
list_1.add(999) #增加
list_1.update([888888888,9999999]) #增加
print(list_1)
list_1.remove(888888888) #删除不存在的元素会报错
print(len(list_1)) #set的长度
print(34 in list_1) #判断是否在集合
print(list_1.pop()) #删除元素并把该元素返回
print(list_1.pop()) #删除元素并把该元素返回
list_1.discard(77) #删除指定值 有则删除 无则不操作
print(list_1)
Python集合基本用法
最新推荐文章于 2024-01-16 08:00:00 发布