集合是无序的,不重复的且不可以更改的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:
这里需要注意,我们不可以直接用花括号"{}"
>>> st=set()
>>> st
set()
>>> st1={}
>>> type(st),type(st1)
(<class 'set'>, <class 'dict'>)
>>>
>>> st={"a","b","c","d","e"}
>>> st,type(st)
({'a', 'd', 'b', 'c', 'e'}, <class 'set'>)
>>>
>>> li=[1,"a","n","university"]
>>> st_li=set(li)
>>> st_li,type(st_li)
({1, 'n', 'university', 'a'}, <class 'set'>)
>>>
>>> str="universitysity"
>>> st_str=set(str)
>>> st_str,type(st_str)
({'v', 'r', 'i', 'n', 'y', 'e', 's', 'u', 't'}, <class 'set'>)
>>>
>>> dic={"a":1,"b":2,"c":3,"d":4}
>>> st_dic=set(dic)
>>> st_dic,type(dic)
({'d', 'b', 'c', 'a'}, <class 'dict'>)
>>>
>>> tp=(1,2,3,4)
>>> st_tp=set(tp)
>>> st_tp,type(st_tp)
({1, 2, 3, 4}, <class 'set'>)
>>>
无序,不可查找
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st[2]
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'set' object does not support indexing
>>>
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st.add("Computer Science")
>>> st
{1, 2, 'Computer Science', 'Yingxiao', 'Hunan', 'College'}
>>> st.update("湖南","长沙")
>>> st
{1, 2, '长', 'Computer Science', 'Yingxiao', 'Hunan', '南', 'College', '沙', '湖'}
>>>
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st.pop()#删除排序最小的一个元素
1
>>> st
{2, 'Yingxiao', 'Hunan', 'College'}
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st.discard(2)#移除元素
>>> st
{1, 'Yingxiao', 'Hunan', 'College'}
>>> st.discard("Hunan")#移除元素
>>> st
{1, 'Yingxiao', 'College'}
>>> st.discard("YiYang")#如果集合中不包含此元素就不会做出任何操作
>>> st
{1, 'Yingxiao', 'College'}
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st.remove(2)
>>> st
{1, 'Yingxiao', 'Hunan', 'College'}
>>> st.remove("HUNAN")#如果此元素不被包含在内就会报错
Traceback (most recent call last):
File "" , line 1, in <module>
KeyError: 'HUNAN'
>>>
>>> st={1,2,3}
>>> st.clear()
>>> st
set()
>>> st={1,2,3}
>>> del st
>>> st
Traceback (most recent call last):
File "" , line 1, in <module>
NameError: name 'st' is not defined
>>>
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> st[1]="Hunan"
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'set' object does not support item assignment
>>>
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> for i in st:
... print(i,end=" ")
...
1 2 Yingxiao Hunan College >>>
>>>
>>> st={1,2,"Hunan","Yingxiao","College"}
>>> for index,value in enumerate(st):
... print(index,value)
...
0 1
1 2
2 Yingxiao
3 Hunan
4 College
>>>
>>> a=set("abcd")
>>> b=set("cdef")
>>> c=set("ab")
>>> a,b,c
({'d', 'b', 'c', 'a'}, {'d', 'c', 'f', 'e'}, {'b', 'a'})
>>> c.issubset(a)
True
>>> c<a
True
>>> c<b
False
>>>
>>> a=set("abcd")
>>> b=set("cdef")
>>> a.intersection(b)
{'d', 'c'}
>>> a&b
{'d', 'c'}
>>>
>>> a=set("abcd")
>>> b=set("cdef")
>>> a.union(b)
{'a', 'd', 'b', 'c', 'e', 'f'}
>>> a|b
{'a', 'd', 'b', 'c', 'e', 'f'}
>>>
>>> a=set("abcd")
>>> b=set("cdef")
>>> a.difference(b)
{'b', 'a'}
>>> a-b
{'b', 'a'}
>>> b-a
{'f', 'e'}
>>>