- 无序
- 不可重复
- 不可更改
- 内部的元素是可哈希的
- 集合本善不可哈希
- 用{括起来的单元素数据集}
用途:
- 去重(列表—>集合,自动去重)
- 关系测试
集合的创建
空集合的创建
st = set()
print(st, type(st))
st = {}
print(type(st))
'''
set() <class 'set'>
<class 'dict'>
'''
多元素集合的创建
st = {1, 2, 3, "a", "b", "c"}
print(st)
st = {1, 2, 3, "a", "b", "c", ["a", "b"]}
print(st)
'''
{1, 2, 3, 'b', 'a', 'c'}
Traceback (most recent call last):
File "D:/pycharm_test/day04/test.py", line 4, in <module>
st = {1, 2, 3, "a", "b", "c", ["a", "b"]}
TypeError: unhashable type: 'list'
'''
强转
- 列表转为集合
t = {1}
print(type(t))
li = ["city", "college", "zhejiang"]
st = set(li)
print(st, type(st))
'''
<class 'set'>
{'college', 'city', 'zhejiang'} <class 'set'>
'''
- 字符串转为集合(结果为无序排列)
sr = "city"
st = set(sr)
print(st) # 无序
'''
{'i', 'c', 'y', 't'}
'''
sr = "hello"
st = set(sr)
print(st)
'''
{'l', 'h', 'o', 'e'}
'''
- 字典转为集合(结果为无序排列)
dic = {"id": 20190101, "name": "Tom", "age": 18}
st = set(dic)
print(st, type(st))
'''
{'age', 'id', 'name'} <class 'set'>
'''
dic = {"id": 20190101, "name": "Tom", "age": 18}
li = list(dic)
print(li)
'''
['id', 'name', 'age'] #字典转为列表为有序
'''
集合的基本操作
增
-
set.add()
-
set.updata()
删
- set.pop(),删除排序最小的一个元素
st = {"d", "c", "a", "b"}
print(st.pop())
'''
a
'''
- set.discard(),移除元素,不存在,不会报错
st = {"d", "c", "a", "b"}
print(st.discard("f"))
'''
None
'''
- set.remove(),移除元素,不存在,报错
st = {"d", "c", "a", "b"}
print(st.remove("f"))
'''
KeyError: 'f'
'''
-
del set
删除整个集合
改
不可更改
查
无序,不可查
遍历
st = {"city", "college", "zhejiang"}
for i in st:
print(i)
'''(无序)
zhejiang
college
city
'''
for i in enumerate(st):
print(i)
'''(无序)
(0, 'zhejiang')
(1, 'college')
(2, 'city')
'''
集合的基本运算
子集
a = set("abcd")
b = set("cdef")
c = set("ab")
print(a, b, c)
print(c < a)
print(c.issubset(a))
print(c < b)
print(a>c)
'''
{'c', 'd', 'a', 'b'} {'f', 'e', 'c', 'd'} {'a', 'b'}
True
True
False
True
'''
交集
- &
a = set("abcd")
b = set("cdef")
c = set("ab")
print(a&b)
'''
{'d', 'c'}
'''
- set.intersection()
print(a.intersection(b))
print(b.intersection(c))
'''
{'c', 'd'}
set()
'''
并集
- |
a = set("abcd")
b = set("cdef")
c = set("ab")
print(a|b)
'''
{'c', 'a', 'd', 'f', 'b', 'e'}
'''
- set.union()
a = set("abcd")
b = set("cdef")
c = set("ab")
print(a.union(b))
'''
{'e', 'f', 'd', 'c', 'a', 'b'}
'''
差集
a = set("abcd")
b = set("cdef")
c = set("ab")
print(a - c)
'''
{'c', 'd'}
'''
- set.difference()
print(a.difference(c))
print(c.difference(a))
'''
{'d', 'c'}
set()
'''