day04_集合

集合(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'}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值