python--集合
重点:
- 集合去掉重复的元素(简称去重)
- 集合无序
- 集合里的元素是可哈希的
- 集合关系测试
- 把序列分成集合中的若干个元素
1、字符串集合,把字符串的每个字符分成若干个集合的元素
a = set('chen') print(a) 输出: {'c', 'e', 'n', 'h'}
2、集合去重
a = set('chench') print(a) 输出: {'h', 'c', 'n', 'e'}
3、集合的增
set().add() #参数是可哈希的参数
a = set(['chen','liang']) a.add('zhang') print(a) 输出: {'chen', 'zhang', 'liang'}
set().update()
a = set(['chen','liang']) a.update(['zhang',21]) print(a) 输出: {'zhang', 'chen', 21, 'liang'}
update()与add()的区别:
add()如果是一个字符串作参数是把参数作为一个整体放到集合中作元素,而update()是把字符串拆开且每个字符都作为集合中的元素
4、集合的删
set().pop() #默认删除任意一个
a = set(['chen','liang']) a.pop() print(a) 输出: {'liang'}
set().remove()
a = set(['chen','liang']) a.remove('liang') #如果删除的元素在集合中没有会发生错误
print(a)
输出: {'chen'}
set().discard()
a = set(['chen','liang']) a.discard('chen') #如果删除的元素在集合中没有也不会发生错误 print(a) 输出: {'liang'}
set().clear() #清空集合中的元素
a = set(['chen','liang']) a.clear() print(a) 输出: set()
6、判断元素是否在集合中存在
a = set(['chen','liang']) print('chen' in a) print('zhang' in a) 输出: True False
7、差集
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) c = a.difference(b) #等价于c = a-b print(c) 输出: {1, 2, 3}
8、交集
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) c = a.intersection(b) #等价于c = a&b print(c) #输出: {4, 5}
9、并集
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) c = a.union(b) #等价于c = a|b print(c) #输出: {1, 2, 3, 4, 5, 6, 7, 8}
10、对称差集
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) c = a.symmetric_difference(b) print(c) #输出: {1, 2, 3, 6, 7, 8}
11、判断指定集合是否为该方法参数集合的子集。
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) b1 = set([4,5]) c = a.issubset(b) d = b1.issubset(a) print(c,d) #输出: False True
12、判断该方法的参数集合是否为指定集合的子集
a = set([1,2,3,4,5]) b = set([4,5,6,7,8]) b1 = set([4,5]) c = a.issuperset(b1) print(c) #输出: True