集合set
1.集合是无序的,集合是不重复的
2.集合里面的元素必须是可哈希的,但是它本身是不可哈希的
3.集合不能更改里面的元素
4.集合可以求交集、并集、差集、反交集等
去重
1,用算法去做
2,转换成集合,再转换过来.
lis = [1,1,2,2,3,3,3,4,5,6,6,7] set1 = set(lis) lis = list(set1) print(lis)
1,集合的创建。
set1 = set({1,2,‘barry‘}) set2 = {1,2,‘barry‘} print(set1,set2) # {1, 2, ‘barry‘} {1, 2, ‘barry‘}
2,集合的增
set1 = {‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.add(‘景女神‘) print(set1) #update:迭代着增加 set1.update(‘A‘) print(set1) set1.update(‘老师‘) print(set1) set1.update([1,2,3]) print(set1)
3,集合的删
set1 = {‘alex‘,‘wusir‘,‘ritian‘,‘egon‘,‘barry‘} set1.remove(‘alex‘) # 删除一个元素 print(set1) set1.pop() # 随机删除一个元素 print(set1) set1.clear() # 清空集合 print(set1) del set1 # 删除集合 print(set1)
4,集合的其他操作:
4.1 交集。(& 或者 intersection)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 & set2) # {4, 5} print(set1.intersection(set2)) # {4, 5}
4.2 并集。(| 或者 union)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 | set2) # {{1, 2, 3, 4, 5, 6, 7, 8} print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7, 8}
4.3 差集。(- 或者 difference)
set1-set2 set1独有的
set2-set1 set2独有的
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 - set2) # {1, 2, 3} print(set1.difference(set2)) # {1, 2, 3}
4.4反交集。 (^ 或者 symmetric_difference)
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 ^ set2) # {1, 2, 3, 6, 7, 8} print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}
4.5子集与超集
set1 = {1,2,3} set2 = {1,2,3,4,5,6} print(set1 < set2) print(set1.issubset(set2)) # 这两个相同,都是说明set1是set2子集。 print(set2 > set1) print(set2.issuperset(set1)) # 这两个相同,都是说明set2是set1超集。
5,frozenset不可变集合,让集合变成不可变类型
s = frozenset(‘barry‘) print(s,type(s)) # frozenset({‘a‘, ‘y‘, ‘b‘, ‘r‘}) <class ‘frozenset‘>