python中,用set來表示一個(gè)無序不重復(fù)元素的序列。set的主要作用就是用來給數(shù)據(jù)去重。
可以使用大括號{}或者set()函數(shù)創(chuàng)建集合,但是注意如果創(chuàng)建一個(gè)空集合必須用set()而不是{},因?yàn)閧}是用來表示空字典類型的。
set的集合的創(chuàng)建與使用
#1.用{}創(chuàng)建set集合
person={"student","teacher","babe",123,321,123}#同樣各種類型嵌套,可以賦值重復(fù)數(shù)據(jù),但是存儲會去重
print(len(person))#存放了6個(gè)數(shù)據(jù),長度顯示是5,存儲是自動去重.
print(person)#但是顯示出來則是去重的
'''
5
{321,'teacher','student','babe',123}
'''
#空set集合用set()函數(shù)表示
person1=set()#表示空set,不能用person1={}
print(len(person1))
print(person1)
'''
0
set()
'''
#3.用set()函數(shù)創(chuàng)建set集合
person2=set(("hello","jerry",133,11,133,"jerru"))#只能傳入一個(gè)參數(shù),可以是list,tuple等類型
print(len(person2))
print(person2)
'''
5
{133,'jerry',11,'jerru','hello'}
'''
以上內(nèi)容為大家介紹了python培訓(xùn)之空集合如何表示,希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。