Python 中的集合 --set

前言

在Python中,我们用[]来表示列表list,用()来表示元组tuple,那{}呢?{}不光可用来定义字典dict,还可以用来表示集合set

集合 set

集合(set)是一个无序的不重复元素序列,集合中的元素不能重复且没有顺序,所以不能通过索引和分片进行操作。

如何创建set

•set() 创建一个集合,需要提供一个序列(可迭代的对象)作为输入参数:

#字符串
>>> set('abc')
{'a', 'b', 'c'}
#列表
>>> set(['a','b','c'])
{'a', 'b', 'c'}
#元组
>>> set(('a','b','c'))
{'a', 'b', 'c'}

# 集合中的元素不重复
>>> set('aabc')
{'a', 'b', 'c'}

#整数
>>> set(123)

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    set(123)
TypeError: 'int' object is not iterable

•{}

>>> {1,2,3}
{1, 2, 3}
>>> a = {1,2,3}
>>> type(a)
<class 'set'>

但注意 利用 {} 来创建集合不能创建空集合,因为 {} 是用来创造一个空的字典

set的常用方法

扫描二维码关注公众号,回复: 9629615 查看本文章

•set`的添加和删除,更新

>>> a = set('abc')
>>> a
{'a', 'b', 'c'}

#添加元素
>>> a.add('d')
>>> a
{'a', 'b', 'd', 'c'}

#重复添加无效果
>>> a.add('d')
>>> a
{'a', 'b', 'd', 'c'}

#删除元素
>>> a.remove('c')
>>> a
{'a', 'b', 'd'}

#update 把要传入的元素拆分,作为个体传入到集合中
>>> a.update('abdon')
>>> a
{a', 'b', 'd', 'o', 'n' }

set的集合操作符

 

>>> a = set('abc')
>>> b = set('cdef')
>>> a&b
{'c'}
>>> a | b  
{'a', 'b', 'f', 'c', 'd', 'e'}
>>> a -b
{'a', 'b'}
>>> 'a' in a
True
>>> 'e' in a
False
>>> a != b
True
>>> a == b
False

集合还有不可变集合frozenset,用的不多,有兴趣的同学可以自行学习下!

 更多交流公众号:猿桌派

猜你喜欢

转载自www.cnblogs.com/techfix/p/12431696.html