标签:
set集合 set是一个无序且不重复的元素集合
优点:访问速度快,解决重复问题
l1 = [1,2,34,5,6,7,4,3,3,] s2 = set(l1) #可以以列表元祖等作为参数传进来,set集合会自动转换成元祖并去重
#输出结果:
{1, 2, 34, 4, 5, 6, 7, 3}
各种方法:add,clear,.....等等
add 合并集合
l1 = [1,2,34,5,6,7,4,3,3,] l2 = [23,3,4,5,100,2,3] s2 = set(l1) #自动转换并去重 s2.add(67) print(s2)
cear
l1 = [1,2,34,5,6,7,4,3,3,] l2 = [23,3,4,5,100,2,3] s2 = set(l1) #自动转换并去重 s2.add(67) s2.clear() print(s2)
copy
l1 = [1,2,34,5,6,7,4,3,3,] s2 = set(l1) #自动转换并去重 s3 = s2.copy() print(s3) #输出结果: {1, 2, 34, 4, 5, 6, 7, 3}
difference 求差集
l1 = [1,2,34,5,6,7,4,3,3,] s1 = set(l1) #自动转换并去重 s2 = set([12,3465,75,32,2]) s3 = s2.difference(s1) #循环s2里的元素跟s1比较,若不存在s1内就会打印 s4 = s1.difference(s2) #循环s1里的元素跟s2比较,若不存在s1内就会打印 print(s3) print(s4) #输出结果: {32, 3465, 75, 12} {1, 34, 3, 4, 5, 6, 7}
difference_update 与difference的区别是它会更新原来的集合
l1 = [1,2,34,5,6,7,4,3,3,] s1 = set(l1) #自动转换并去重 s2 = set([12,3465,75,32,2]) s2.difference_update(s1) print(s2) #输出结果: {32, 3465, 75, 12}
discard 参数为一个字符串或者一个数字,如果该参数在集合内,则删除,若不在,则没有任何操作
#清除的元素不存在,不采取任何操作
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s1.discard(‘abc‘) print(s1) #输出结果: {1, 2, 34, 4, 5, 6, 7, 3, ‘a‘, ‘ab‘} #参数存集合内,则清除该元素 l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s1.discard(‘ab‘) print(s1) #输出结果: {1, 2, 34, 4, 5, 6, 7, 3, ‘a‘}
intersection 取两个结合之间的交集
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([1,2,23,3,3,5,2]) s3 = s2.intersection(s1) print(s3) #输出结果:
{1, 2, 3, 5}
intersection_update 功能与intersection一样,区别是它会更新原来的集合
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([1,2,23,3,3,5,2]) s2.intersection_update(s1) print(s2) #输出结果 {1, 2, 3, 5}
isdisjoint 如果没有交集就返回True,反之则返回False
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([1,2,23,3,3,5,2]) s3 = s2.isdisjoint(s1) print(s3) #输出结果 False l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([111,222]) s3 = s2.isdisjoint(s1) print(s3) #输出结果 True
issubset 是否是子集,是则返回True,否则返回False
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([111,222]) s3 = s2.issubset(s1) print(s3) #输出结果: False
issuperset 是否是父集,是则返回True,否则返回False
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘] s1 = set(l1) #自动转换并去重 s2 = set([111,222]) s3 = s2.issuperset(s1) print(s3) #输出结果: False
pop 随意删除一个元素并返回
l1 = [1,2,34,5,6,7,4,3,3,‘a‘,‘ab‘,‘ds‘] s1 = set(l1) #自动转换并去重 s2 = s1.pop(2) print(s2) #输出结果 随意的结果
remove 删除一个指定的元素,不返回
l1 = [‘a‘,‘ab‘,‘ds‘] s1 = set(l1) #自动转换并去重 s1.remove(‘a‘) print(s1) #输出结果 {‘ab‘, ‘ds‘}
symmetric_difference 对称差值,指将两个集合合并后再求差集
l1 = [‘a‘,‘ab‘,‘ds‘] s1 = set(l1) #自动转换并去重 s2 = set([1,2,3,4,‘c‘,‘d‘,‘a‘]) s3 = s1.symmetric_difference(s2) s4 = s2.symmetric_difference(s1) print(s3) print(s4) #两次打印的结果是一样的 {1, 2, 3, 4, ‘d‘, ‘c‘, ‘ab‘, ‘ds‘} {1, 2, 3, 4, ‘d‘, ‘ds‘, ‘c‘, ‘ab‘}
symmetric_difference_update 与symmetric_difference 功能一样,只是它要更新原来的集合
update 更新某个元素
l1 = [‘a‘,‘ab‘,‘ds‘] s1 = set(l1) #自动转换并去重 s1.update(‘cd‘) print(s1) #输出结果: {‘d‘, ‘ab‘, ‘ds‘, ‘a‘, ‘c‘}
标签:
原文地址:http://www.cnblogs.com/zhaojianbo/p/5140836.html