集合(set())

集合(set())

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

用途

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

集合的创建

空集合的创建

st= set()

print(st)

set()

st=set()
print(st)

st={}
print(type(st))
#
set()
<class 'dict'>
t={1}
print(type(t))
#
<class 'set'>

单元素集合

多元素集合

强转

li=["city","college","zhejiang"]
st=set(li)
print(st,type(st))
sr="city"
st=set(sr)
print(st)
sr="hello"
st=set(sr)
print(st)
dic={"id":20190101,"name":"tom","age":18}
st=set(dic)
print(st)
#
{'zhejiang', 'city', 'college'} <class 'set'>
{'i', 'y', 't', 'c'}
{'e', 'l', 'o', 'h'}
{'name', 'id', 'age'}

集合的基本操作

  • set.add()
  • set.update()

  • set.pop()删除排序最小的一个元素

  • set.discard(),移除元素,不存在,不会报错

  • set.remove(),移除元素,不存在报错

  • del set

  • st={"a","b","c","d"}
    print(st.pop())
    print(st)
    st={"a","b","c","d"}
    st.discard("a")
    print(st)
    st={"a","b","c","d"}
    st.remove("a")
    print(st)
    #
    a
    {'c', 'd', 'b'}
    {'c', 'd', 'b'}
    {'c', 'd', 'b'}
    
    

不可改的

不可查的

遍历

st={"city","college","zhejiang"}
for i in st:
    print(i,end=" ")
    #
    zhejiang city college 
st={"city","college","zhejiang"}
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))
#
{'d', 'c', 'b', 'a'} {'d', 'e', 'c', 'f'} {'b', 'a'}
True
True

交集

  • &

  • set.intersection()

  • a=set("abcd")
    b=set("cdef")
    c=set("ab")
    print(a&b)
    print(a.intersection(b))
    #
    {'c', 'd'}
    {'c', 'd'}
    

并集

  • |

  • set.union()

  • a=set("abcd")
    b=set("cdef")
    c=set("ab")
    print(a|b)
    print(a.union(b))
    #
    {'c', 'a', 'f', 'd', 'b', 'e'}
    {'c', 'a', 'f', 'd', 'b', 'e'}
    

差集

  • set.difference()

  • a=set("abcd")
    b=set("cdef")
    c=set("ab")
    print(a-c)
    print(a.difference(c))
    #
    {'d', 'c'}
    {'d', 'c'}
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值