点击返回Python数据分析从入门到精通系列主页
集合(set)是一个无序的不重复元素序列。
创建集合
使用大括号或者set()函数创建集合:
>>> set = set(('hello','python','xiaoyao'))
>>> set
{'python', 'xiaoyao', 'hello'}
>>> aSet = {'hello','python','world'}
>>> aSet
{'python', 'world', 'hello'}
>>>
添加元素
>>> set.add('add')
>>> set
{'python', 'add', 'xiaoyao', 'hello'}
>>>
删除元素
>>> set.remove('add') #移除元素
>>> set
{'python', 'xiaoyao', 'hello'}
>>>
>>> set.discard('hello') #移除元素,如果元素不存在,不会报错
>>> set
{'python', 'xiaoyao'}
>>>
>>> set.pop() #set的pop方法会对集合进行无序排列,然后将左面第一个元素进行删除。
'python'
>>> set
{'xiaoyao'}
>>>
清空集合
>>> set.clear()
>>> set
set()
>>>
集合遍历
>>> for x in aSet:
... print(x)
...
python
world
hello
>>>
获取集合长度
>>> len(aSet)
3
>>>
判断元素是否在集合中
>>> 'hello' in aSet
True
>>>
集合内置方法完整列表
方法 | 描述 |
---|---|
add() | 为集合添加元素 |
clear() | 移除集合中的所有元素 |
copy() | 拷贝一个集合 |
difference() | 返回多个集合的差集 |
difference_update() | 移除集合中的元素,该元素在指定的集合也存在。 |
discard() | 删除集合中指定的元素 |
intersection() | 返回集合的交集 |
intersection_update() | 返回集合的交集。 |
isdisjoint() | 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 |
issubset() | 判断指定集合是否为该方法参数集合的子集。 |
issuperset() | 判断该方法的参数集合是否为指定集合的子集 |
pop() | 随机移除元素 |
remove() | 移除指定元素 |
symmetric_difference() | 返回两个集合中不重复的元素集合。 |
symmetric_difference_update() | 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 |
union() | 返回两个集合的并集 |
update() | 给集合添加元素 |