集合(set)
- 无序
- 不可重复
- 不可更改
- 内部的元素是可哈希的
- 集合本身是不可哈希的
用途:
- 去重(列表—>集合,自动去重)
- 关系测试
集合的创建
空集合的创建
>>>st=set()
>>>st
set()
>>>st={}
>>>type(st)
<class'dict'>
>>>
多元素的集合创建
>>> st={1,2,3,"a","b","c"}
>>> type(st)
<class 'set'>
>>> st={1,2,3,"a","b","c",["a","b"]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
强转
集合的基本操作
增
- set.add()
- set.update()
删
-
set.pop(),随机删除一个元素#集合是无序的
-
set.remove(),删除指定内容,不存在,会报错
-
set.discard(),移除元素,不存在,不会报错
-
del set
-
set.clear()
>>> st={1,2,3,"a","b","c"} >>> st.pop() 'a' >>> st={"a","b","c",1} >>> st.pop() 'a' >>> st={1,2,3,"a","b","c"} >>> st.remove(1) >>> st {'a', 2, 3, 'c', 'b'} >>> st {'a', 2, 3, 'c', 'b'} >>> st.discard(2) >>> st {'a', 3, 'c', 'b'} >>> st.remove(4) Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 4 >>> st.discard(4)
遍历
st={"a","b","c"}
for i in st:
print(i,end=" ")
abc
for i in enumerate()
集合的基本运算
子集
-
,
-
set.issubset(),判断是否为子集
-
<,判断是否为子集
a=set("abcd")
b=set("cdef")
c=set("ab")
a,b,c
({'a', 'b', 'd', 'c'}, {'f', 'e', 'c', 'd'}, {'a', 'b'})
c<a
True
c.issubset(a)
True
c<b
False
交集
-
&
-
set.intersection()
a=set("abcd") b=set("cdef") c=set("ab") a&b {'c','d'} a.intersection(b) {'c','d'}
并集
-
|
-
set.union()
>>> a=set("abcd") >>> b=set("cdef") >>> a|b {'a', 'd', 'e', 'c', 'f', 'b'} >>> a.union(b) {'a', 'd', 'e', 'c', 'f', 'b'}
差集
-
-
set.difference()
>>> a=set("abcd") >>> b=set("cdef") >>> a-b {'a', 'b'} >>> a.difference(b) {'a', 'b'}