目录
- >>> s1 = {1,2,3}
- >>> type(s1)
- <class 'set'>
集合可以看做只有key的字典
1.无序
2.集合元素必须是可hash的,天生去重、
3.可变数据类型
- >>> s2 = set([1,2,2,3,4,5,6])
- >>> s2
- {1, 2, 3, 4, 5, 6}
- >>> s2 = {1,[2,3]}
- Traceback (most recent call last):
- File "
" , line 1, in - TypeError: unhashable type: 'list'
只能添加一项
- >>> s1
- {1, 2, 3}
- >>> s1.add(4)
- >>> s1
- {1, 2, 3, 4}
可添加多项,必须要传入可迭代对象
- >>> s1.update(['a','b'])
- >>> s1
- {1, 2, 3, 4, 'a', 'b'}
删除指定元素
如果指定元素按不存在,就会报错
- >>> s1
- {1, 2, 3, 4, 'a', 'b'}
- >>> s1.remove("a")
- >>> s1
- {1, 2, 3, 4, 'b'}
- >>> s1.remove("v")
- Traceback (most recent call last):
- File "
" , line 1, in - KeyError: 'v'
删除指定元素
如果指定元素按不存在,不会报错
- >>> s1
- {1, 2, 3, 4, 'b'}
- >>> s1.discard(1)
- >>> s1
- {2, 3, 4, 'b'}
- >>> s1.discard(7)
- >>> s1 = {1,2,3}
- >>> s2 = {2,3,4}
- >>> s1 | s2
- {1, 2, 3, 4}
- >>> s1 & s2
- {2, 3}
- >>> s1 - s2
- {1}
- >>> s1 ^ s2
- {1, 4}
- >>> max({1,2,3})
- 3
- >>> min({1,2,3})
- 1
- >>> sum({1,2,3})
- 6