python集合

  • 无序
  • 不可重复
  • 不可更改
    • 内部的元素是可哈希的
    • 集合本善不可哈希
  • 用{括起来的单元素数据集}

用途:

  • 去重(列表—>集合,自动去重)
  • 关系测试

集合的创建

空集合的创建

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()
'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值