1.创建集合 set()
>>>set('python')
{'o', 'p', 'h', 'n', 't', 'y'}
>>>set(['python'])
{'python'}
#去重
>>>list1 = [11, 11, 12, 13, 14, 14, 15]
>>>set(list1)
{11, 12, 13, 14, 15}
2.添加 add(),update()
#add():把传入的元素做为一个整体添加到集合中
>>>set1 = set('python')
>>>set1
{'o', 'p', 'h', 'n', 't', 'y'}
>>>set1.add('java')
>>>set1
{'o', 'p', 'h', 'n', 't', 'java', 'y'}
#update():把传入的元素拆分,做为个体添加到集合中
>>>set2 = set('python')
>>>set2.update('java')
>>>set2
{'o', 'p', 'j', 'a', 'h', 'n', 'v', 't', 'y'}
**3.删除 remove()
set([‘y’, ‘python’, ‘b’, ‘o’])
>>>set1
{'o', 'p', 'h', 'n', 't', 'java', 'y'}
>>>set1.remove('java')
>>>set1
{'o', 'p', 'h', 'n', 't', 'y'}
4.set() 集合操作符号、数学符号
python符号 | 数学符号 | 含义 |
---|---|---|
- | -或\ | 差集 |
& | ∩ | 交集 |
l | ∪ | 并集 |
^ | 对称差,并集减去交集 | |
!= | ≠ | 不等于 |
== | = | 等于 |
in | ∈ | 属于 |
not in | ∉ | 不属于成员 |
5. 函数操作
>>> x
set(['i', 'h', 'j', 'e', 't'])
>>> s = set("hi")
>>> s
set(['i', 'h'])
>>> len(x) #长度
>>> 'i' in x
True
>>> s.issubset(x) #s是否为x的子集
True
>>> y
set(['i', 'e', 'm', 'd', 't'])
>>> x.union(y) #交
set(['e', 'd', 'i', 'h', 'j', 'm', 't'])
>>> x.intersection(y) #并
set(['i', 'e', 't'])
>>> x.difference(y) #差
set(['h', 'j'])
>>> x.symmetric_difference(y) #对称差
set(['d', 'h', 'j', 'm'])
>>> s.update(x) #更新s,加上x中的元素
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.add(1) #增加元素
>>> s
set([1, 'e', 't', 'i', 'h', 'j'])
>>> s.remove(1) #删除已有元素,如果没有会返回异常
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.remove(2)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
s.remove(2)
KeyError: 2
>>> s.discard(2) #如果存在元素,就删除;没有不报异常
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.clear() #清除set
>>> s
set([])
>>> x
set(['i', 'h', 'j', 'e', 't'])
>>> x.pop() #随机删除一元素
'i'
>>> x
set(['h', 'j', 'e', 't'])
>>> x.pop()
'h'
小对比
list:增加——append(),extend()整个添加 ;删除——pop()默认删除最后一个,可以传入数字按位置删除,remove()按照元素删除
dict:增加——update();删除——del
set:增加——update(),add();删除——remove()按照元素删除,pop()删除第一个
参考链接:
https://www.iplaypy.com/jichu/set.html
http://www.cnblogs.com/kaituorensheng/p/4511214.html
http://www.cnblogs.com/justbreaking/p/7210164.html