集合是无序的,天生不重复的数据组合,它的作用如下:
去重,即:把一个列表变成集合,就去重了 关系测试,即:测试两组集合的交集、并集和差集等>>> name_1 = [1,2,3,4,7,8,7,10]#把列表转换为集合>>> name_1 = set(name_1)#转换后,去重>>> print(name_1,type(name_1)){1, 2, 3, 4, 7, 8, 10} <class 'set'>
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_2 = [1,3,5,8,10]>>> name_1 = set(name_1)>>> name_2 = set(name_2)#输出结果>>> name_1.intersection(name_2){8, 1, 10, 3}
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_2 = [1,3,5,8,10]>>> name_1 = set(name_1)>>> name_2 = set(name_2)#输出结果>>> name_1.union(name_2){1, 2, 3, 4, 5, 7, 8, 10}
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_2 = [1,3,5,8,10]>>> name_1 = set(name_1)>>> name_2 = set(name_2)#输出结果>>> name_1.difference(name_2){2, 4, 7}
判断一个集合是否是另一个集合的子集
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_3 = [1,2,3,4]>>> name_1 = set(name_1)>>> name_3 = set(name_3)#输出结果>>> name_3.issubset(name_1)True
判断一个集合是否是另一个集合的父集
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_3 = [1,2,3,4]>>> name_1 = set(name_1)>>> name_3 = set(name_3)#输出结果>>> name_1.issuperset(name_3)True
把两个集合没有交集的数值取出来
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_2 = [1,3,5,8,10]>>> name_1 = set(name_1)>>> name_2 = set(name_2)#输出结果>>> name_1.symmetric_difference(name_2){2, 4, 5, 7}
判断两个集合是否有交集,没有交集,则返回True
>>> name_1 = [1,2,3,4,7,8,7,10]>>> name_2 = [1,3,5,8,10]>>> name_3 = [11]>>> name_1 = set(name_1)>>> name_2 = set(name_2)>>> name_3 = set(name_3)#有交集>>> name_1.isdisjoint(name_2)False#无交集>>> name_1.isdisjoint(name_3)True
新闻热点
疑难解答