集合
特点:
- 无序
- 不可重复
- 不可更改
- 内部的元素是可哈希的
- 集合本身是不可哈希的
- 用{}括起来的单元素数据集,不支持索引
用途:
- 去重(列表----->集合,自动去重)
- 关系测试
集合的创建
#空集合的创建
st=set()
print(st)
st={}
print(type(st))
#输出结果:
set() <class 'set'>
{} <class 'dict'>
#多元素集合的创建
st={1,2,3,'hh'}
print(type(st))
#输出结果:
<class 'set'>
#强转
1、列表强转
li=[23,34,'aa','bb']
st=set(li)
print(st,type(st))
#输出结果:
{34, 'bb', 'aa', 23} <class 'set'> #无序的
2、字符串强转
sr="python"
st=set(sr)
print(st,type(st))
#输出结果:
{'n', 'o', 'p', 'y', 'h', 't'} <class 'set'>
3、字典强转
dict={'id': 20190201, 'age': 18, 'name': 'cl'}
st=set(dict)
print(st,type(st))
#输出结果:
{'id', 'age', 'name'} <class 'set'>
集合的基本操作
(1)增
- set.add()
- set.update()
st.add(4)
print(st)
st.update('5')
print(st)
#输出结果:
(add):
{1, 2, 3, 'a', 'hh', '4'}
(update):
{1, 2, 3, 'a', '5', 'hh', '4'}
(2)删
- set.pop():删除排序最小的一个元素
- set.discard()
- set.remove()
- del set
1、
st.pop()
print(st)
#输出结果:
{2, 3, '5', 'a', 'hh', '4'}
2、
st.discard('a')
print(st)
#输出结果:
{2, 3, '5', 'hh', '4'}
3、
st.remove('5')
print(st)
#输出结果:
{2, 3, 'hh', '4'}
(3)改
#不可改
(4)查
#不可查
遍历
st={1,2,3,'hh','a'}
for i in st:
print(i,end=' ')
for i in enumerate(st):
print(i, end=' ')
#输出结果:
1 2 3 hh a
(0, 1) (1, 2) (2, 3) (3, 'hh') (4, 'a')
集合的基本运算
a=set("abc")
b=set("cde")
c=set("ab")
print(a,b,c)
print(c<a)
print(b>a)
print(c.issubset(a))
#输出结果:
{'c', 'a', 'b'} {'e', 'c', 'd'} {'a', 'b'}
True
False
True
交集
- &
- set.intersection()
a=set("abc")
c=set("ab")
print(a & c)
print(a.intersection(c))
#输出结果:
{'a', 'b'}
并集
- |
- set.union()
a=set("abcd")
b=set("cdef")
print(a|b)
print(a.union(b))
#输出结果:
{'e', 'a', 'c', 'b', 'd', 'f'}
差集
- -
- set.difference()
a=set("abcd")
b=set("cdef")
print(b-a)
print(b.difference(a))
#输出结果:
{'f', 'e'}