集合是一个无序的不重复的可迭代对象,集合中的元素都是可哈希的(不可变的)
set([iterable]) 初始化一个集合
>>> set()
set()
>>> set([1,2,3,2,4])
{1, 2, 3, 4}
add(self, *args, **kwargs) 往集合里添加元素
>>> a = {1,2,3}
>>> a.add(4)
>>> a
{1, 2, 3, 4}
clear 清除集合中的所有元素
>>> a = {1,2,3}
>>> a.clear()
>>> a
set()
copy() 对集合进行浅拷贝
>>> a = {1,2,3}
>>> b = a.copy()
>>> b
{1, 2, 3}
difference(iterable) 获取两个集合的差异,返回一个新的集合
>>> a = {1,2,3}
>>> a.difference([1,2,5,6])
{3}
| 获取两个集合的并集,返回一个新的集合
>>> {1,2,3,4} | {1,2,5,6}
{1, 2, 3, 4, 5, 6}
& 获取两个集合的交集,返回一个新的集合
>>> {1,2,3,4} & {1,2,5,6}
{1, 2}
- 获取两个集合的差值,返回一个新的集合
>>> {1,2,3,4} - {1,2,5,6}
{3, 4}
^ 获取两个集合的对称差集 (元素在俩集合中,但不会同时出现在二者中)
>>> a = {1,2,3}
>>> b = {3,5,6}
>>> a^b
{1, 2, 5, 6}
pop 随机取出集合中的一个元素并返回这个元素
{1,2,5,6}.pop()
remove 移除集合中的指定元素,如果元素不存在抛出KeyError异常
>>> a = {1,2,3}
>>> a.remove(1)
>>> a
{2, 3}
>>> a.remove(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 5
difference_update(iterable) 移除集合中所有和可迭代对象重叠的元素
>>> a = {1,2,3}
>>> a.difference_update([1,3,5])
>>> a
{2}
discard() 移除集合中的一个元素,若这个元素不在集合中,没事
>>> a = {1,2,3}
>>> a.discard(3)
>>> a
{1, 2}
>>> a.discard(6)
>>> a
{1, 2}
intersection(iterable) 返回集合和可迭代对象的交集
>>> a = {1,2,3}
>>> a.intersection([1,2,5,6])
{1, 2}
isdisjoint(iterable) 判断集合和可迭代对象中是否有相同的元素
>>> a = {1,2,3}
>>> a.isdisjoint([1,2,5,6])
False
>>> a.isdisjoint([1,2])
False
>>> a.isdisjoint([5,6])
True
issubset(iterable) 判断可迭代对象是否拥有集合中的全部元素
>>> a = {1,2,3}
>>> a.issubset({1})
False
>>> a.issubset({1,2,3,4})
True
>>> a.issubset([1,2,3,4])
True
issuperset(iterable) 判断集合是否拥有可迭代对象中的全部元素
>>> a = {1,2,3}
>>> a.issuperset({1})
True
>>> a.issuperset({1,2,3,4})
False
>>> a.issuperset({0})
False
symmetric_difference(iterable) 返回可迭代对象和集合的对称差集
>>> a = {1,2,3}
>>> a.symmetric_difference([1,2])
{3}
>>> a.symmetric_difference([1])
{2, 3}
>>> a.symmetric_difference([5])
{1, 2, 3, 5}
symmetric_difference_update (iterable) 更新集合,使集合中只保留可迭代对象和集合的对称差集
>>> a = {1,2,3}
>>> a.symmetric_difference_update([1,3,5,6])
>>> a
{2, 5, 6}
union(iterable) 返回可迭代对象和集合的并集
>>> a = {1,2,3}
>>> a.union([1,2,5,6])
{1, 2, 3, 5, 6}
update(iterable) 将可迭代对象中集合中没有的元素更新到集合中
>>> a = {1,2,3}
>>> a.update([1,2,5,6])
{1, 2, 3, 5, 6}