集合(set())

懵懂的女人 提交于 2019-12-01 05:33:03

集合(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'}
    
    
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!