《Python語言程序設(shè)計(jì)》課件-第六章(中英文課件)_第1頁
《Python語言程序設(shè)計(jì)》課件-第六章(中英文課件)_第2頁
《Python語言程序設(shè)計(jì)》課件-第六章(中英文課件)_第3頁
《Python語言程序設(shè)計(jì)》課件-第六章(中英文課件)_第4頁
《Python語言程序設(shè)計(jì)》課件-第六章(中英文課件)_第5頁
已閱讀5頁,還剩92頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

Python語言程序設(shè)計(jì)《字典的定義》PythonLanguageProgrammingDictionaryDefinitions同現(xiàn)實(shí)中的字典相似,Python的字典利用”Key-Value”機(jī)制對(duì)存入字典的數(shù)據(jù)進(jìn)行快速查找定位。案例字典的定義Similartothedictionaryinreality,Python'sdictionaryusesthe"KeyValue"mechanismtoquicklysearchandlocatethedatastoredinthedictionary.Casedictionarydefinitions案例字典的定義dict1={'張三':25,'李四':16,'王五':40}d={key1:value1,key2:value2}【例】一個(gè)簡(jiǎn)單的字典實(shí)例字典注意事項(xiàng):(1)鍵必須是唯一的,但值可以不唯一。(2)值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串、數(shù)字或元組。(3)字典的鍵值是“只讀”的,所以不能對(duì)鍵和值分別進(jìn)行初始化。鍵用列表類型可以嗎?Dict1={'ZhangSan':25,'LiSi':16,'WangWu':40}d={key1:value1,key2:value2}[Example]AsimpleexampleofadictionarythatDictionaryNotes.(1)Thekeymustbeunique,butthevaluemaynotbeunique.(2)Thevaluecantakeanydatatype,butthekeymustbeimmutable,suchasastring,numberortuple.(3)Thekeysandvaluesofthedictionaryare"read-only",sothekeysandvaluescannotbeinitializedseparately.Isitokaytousealisttypeforkeys?Casedictionarydefinitions案例字典的定義dic={}dic.keys=(1,2,3,4,5,6)dic.values=("a","b","c","d","e","f")【例】值是只讀的,不可以修改AttributeError:'dict'objectattribute'keys'isread-onlyAttributeError:'dic'objectattribute'values'isread-onlydic={}dic.keys=(1,2,3,4,5,6)dic.values=("a","b","c","d","e","f")[Example]Thevalueisread-onlyandcannotbemodifiedAttributeError:'dict'objectattribute'keys'isread-onlyAttributeError:'dic'objectattribute'values'isread-onlyCasedictionarydefinitions問題1:鍵必須是唯一還是不唯一的?唯一的問題2:字典中的Value值可以重復(fù)嗎?提問可以Question1:Dokeyshavetobeuniqueornon-unique?TheoneandonlyQuestion2:Canthevalueinthedictionaryberepeated?AskaquestionYes,youcan問題3:字典中的鍵用列表類型可以嗎?提問值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串、數(shù)字或元組Question3:Isitoktousealisttypeforkeysinadictionary?Thevaluecantakeanydatatype,butthekeymustbeimmutable,suchasastring,number,ortupleAskaquestionPython語言程序設(shè)計(jì)《訪問字典里的值》PythonLanguageProgrammingAccesstoDictionaryValues案例訪問字典里的值dict={'Name':'DerisWeng','Age':7,'Class':'First'}print("dict['Name']:",dict['Name'])print("dict['Age']:",dict['Age'])訪問字典中的值可以通過dict[Key]的方式,即把相應(yīng)的鍵放到方括弧[]中進(jìn)行訪問?!纠客ㄟ^直接引用訪問字典中的值dict['Name']:DerisWengdict['Age']:7Toaccessthevaluesinthedictionarydict={'Name':'DerisWeng','Age':7,'Class':'First'}print("dict['Name']:",dict['Name'])print("dict['Age']:",dict['Age'])Thevaluesinthedictionarycanbeaccessedbydict[Key],thatis,placingthecorrespondingkeyinthesquarebracket[].[Example]Accessingavalueinadictionarybydirectreferencedict['Name']:DerisWengdict['Age']:7Case案例訪問字典里的值dict={'Name':'DerisWeng','Age':7,'Class':'First'}print("dict['Christopher']:",dict['Christopher'])如果使用字典里沒有對(duì)應(yīng)的鍵,則訪問數(shù)據(jù)時(shí)會(huì)報(bào)錯(cuò)。【例】訪問字典中沒有的鍵Traceback(mostrecentcalllast):File"test1.py",line5,in<module>print("dict['Christopher']:",dict['Christopher'])KeyError:'Christopher'dict={'Name':'DerisWeng','Age':7,'Class':'First'}print("dict['Christopher']:",dict['Christopher'])Ifyouuseadictionarythatdoesnothaveacorrespondingkey,youwillgetanerrorwhenaccessingthedata.[Example]AccessingakeythatisnotinthedictionaryTraceback(mostrecentcalllast):File"test1.py",line5,in<module>print("dict['Christopher']:",dict['Christopher'])KeyError:'Christopher'ToaccessthevaluesinthedictionaryCase案例訪問字典里的值dict={'Name':'DerisWeng','Age':7,'Class':'First'}print(“dict[‘Christopher’]:”,dict.get(‘Christopher’))利用get方法訪問【例】利用get方法,訪問字典中沒有的鍵dict[‘Christopher’]:Nonedict={'Name':'DerisWeng','Age':7,'Class':'First'}print(“dict[‘Christopher’]:”,dict.get(‘Christopher’))Accesswithgetmethod[Example]Usethegetmethodtoaccesskeysnotinthedictionarydict[‘Christopher’]:NoneToaccessthevaluesinthedictionaryCase問題:根據(jù)key得到value的方法有哪幾種?dict[Key]dict.get(Key)提問Question:Whatarethemethodstogetthevalueaccordingtothekey?dict[Key]dict.get(Key)AskaquestionPython語言程序設(shè)計(jì)《修改字典》PythonLanguageProgrammingModifyingDictionaries案例修改字典dict={'Name':'DerisWeng','Age':7,'Class':'First'}dict['Age']=18;

dict['School']="WZVTC"

print("dict['Age']:",dict['Age'])print("dict['School']:",dict['School'])通過直接引用賦值的方式對(duì)字典進(jìn)行修改【例】修改字典dict['Age']:18dict['School']:WZVTC#更新Age#添加信息CaseModifythedictionarydict={'Name':'DerisWeng','Age':7,'Class':'First'}dict['Age']=18;

dict['School']="WZVTC"

print("dict['Age']:",dict['Age'])print("dict['School']:",dict['School'])modificationstothedictionarybydirectreferenceassignment[Example]Modifythedictionarydict['Age']:18dict['School']:WZVTC#UpdateAge#Addinformation問題:對(duì)字典進(jìn)行修改時(shí),key在字典中存在與不存在會(huì)有什么區(qū)別?如果dict[Key]中的Key在字典中不存在,則賦值語句將向字典中添加新內(nèi)容,即增加新的鍵值對(duì);如果dict[Key]中的Key在字典中存在,則賦值語句將修改字典中的內(nèi)容。提問Question:Whenmodifyingadictionary,whatisthedifferencebetweentheexistenceandnonexistenceofakeyinthedictionary?Ifthekeyindict[Key]doesnotexistinthedictionary,theassignmentstatementwilladdnewcontenttothedictionary,thatis,addanewkeyvaluepair;Ifthekeyindict[Key]existsinthedictionary,theassignmentstatementwillmodifythecontentinthedictionary.AskaquestionPython語言程序設(shè)計(jì)《刪除字典元素》PythonLanguageProgrammingDeletingDictionaryElements31可以用del命令刪除單一的元素或者刪除整個(gè)字典,也可以用clear清空字典?!纠縿h除字典元素dict={'Name':'Runoob','Age':7,'Class':'First'}

deldict[‘Name’]#刪除鍵‘Name’dict.clear()#刪除字典deldict#刪除字典print(“dict[‘Age’]:”,dict[‘Age’])print(“dict[‘School’]:”,dict[‘School’])會(huì)發(fā)生異常,因?yàn)閳?zhí)行del操作后字典不再存在。案例刪除字典元素32Youcanusethedelcommandtodeleteasingleelementordeletetheentiredictionary,orclearthedictionary.[Example]Deletingdictionaryelementsdict={'Name':'Runoob','Age':7,'Class':'First'}

Deldict['Name']#Deletekey'Name'Dict.clear()#DeletedictionaryDeldict#Deletedictionaryprint(“dict[‘Age’]:”,dict[‘Age’])print(“dict[‘School’]:”,dict[‘School’])Anexceptionoccursbecausethedictionarynolongerexistsafterthedeloperation.DeletingdictionaryelementsCasePython語言程序設(shè)計(jì)《字典鍵的特性》PythonLanguageProgrammingCharacterizationofDictionaryKeys35兩個(gè)重要的點(diǎn)需要記?。骸纠恐貜?fù)出現(xiàn)的情況dict={'Name':'DerisWeng','Age':7,'Name':'DerisWeng'}

print(“dict[‘Name’]:”,dict[‘Name’])dict[‘Name’]:DerisWeng1)不允許同一個(gè)鍵出現(xiàn)兩次。創(chuàng)建時(shí)如果同一個(gè)鍵被賦值兩次,后一個(gè)值會(huì)被記住。案例字典鍵的特性36Twoimportantpointstoremember.[Example]Repeatedoccurrencesdict={'Name':'DerisWeng','Age':7,'Name':'DerisWeng'}

print(“dict[‘Name’]:”,dict[‘Name’])dict[‘Name’]:DerisWeng1)Donotallowthesamekeytoappeartwice.Ifthesamekeyisassignedtwiceduringcreation,thelattervaluewillberemembered.CharacterizationofdictionarykeysCase37兩個(gè)重要的點(diǎn)需要記?。骸纠坎荒苡昧斜碜鳛殒Idict={['Name‘]:'DerisWeng','Age':7}

print(“dict[‘Name’]:”,dict[‘Name’])報(bào)錯(cuò)2)鍵必須不可變,所以可以用數(shù)字,字符串或元組充當(dāng),而用列表就不行。案例字典鍵的特性38[Example]Youcan'tusealistasakeydict={['Name‘]:'DerisWeng','Age':7}

print(“dict[‘Name’]:”,dict[‘Name’])Reportanerror2)Thekeymustbeimmutable,soitcanbefilledwithnumbers,stringsortuples,butnotwithlists.CharacterizationofdictionarykeysCaseTwoimportantpointstoremember.Python語言程序設(shè)計(jì)39《字典的方法》PythonLanguageProgramming40TheDictionaryApproach41【字典的方法】知識(shí)點(diǎn)6dict.clear()

刪除字典內(nèi)所有元素dict.copy()

返回一個(gè)字典的淺復(fù)制dict.fromkeys()

創(chuàng)建一個(gè)新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對(duì)應(yīng)的初始值dict.get(key,default=None)

返回指定鍵的值,如果值不在字典中返回default值keyindict

如果鍵在字典dict里返回true,否則返回false2字典知識(shí)要點(diǎn)42[Dictionarymethod]Knowledgepoint6dict.clear()

Deleteallelementsinthedictionarydict.copy()

Returnsashallowcopyofadictionarydict.fromkeys()

Createanewdictionary,usetheelementsinthesequenceseqasthedictionarykeys,andvalistheinitialvaluecorrespondingtoallthekeysinthedictionarydict.get(key,default=None)

Returnthevalueofthespecifiedkey.Ifthevalueisnotinthedictionary,returnthedefaultvaluekeyindict

Ifthekeyreturnstrueinthedictionarydict,otherwiseitreturnsfalse2DictionaryKnowledgePoints43radiansdict.items()

以列表返回可遍歷的(鍵,值)元組數(shù)組radiansdict.keys()

以列表返回一個(gè)字典所有的鍵radiansdict.setdefault(key,default=None)

和get()類似,但如果鍵不存在于字典中,將會(huì)添加鍵并將值設(shè)為defaultradiansdict.update(dict2)

把字典dict2的鍵/值對(duì)更新到dict里radiansdict.values()

以列表返回字典中的所有值2字典知識(shí)要點(diǎn)[Dictionarymethod]Knowledgepoint644radiansdict.items()

Returnsanarrayoftraversable(key,value)tuplesasalistradiansdict.keys()

Returnsallthekeysofadictionaryasalistradiansdict.setdefault(key,default=None)

Similartoget(),butifthekeydoesnotexistinthedictionary,thekeywillbeaddedandthevaluewillbesettodefaultradiansdict.update(dict2)

Updatethekey/valuepairofdict2todictradiansdict.values()

Returnsallthevaluesinthedictionaryasalist2DictionaryKnowledgePoints[Dictionarymethod]Knowledgepoint645【字典的方法】知識(shí)點(diǎn)6pop(key[,default])

刪除字典給定鍵key所對(duì)應(yīng)的值,返回值為被刪除的值。key值必須給出。否則,返回default值。popitem()

隨機(jī)返回并刪除字典中的一對(duì)鍵和值。2字典知識(shí)要點(diǎn)46pop(key[,default])

Deletethevaluecorrespondingtothekeygiveninthedictionary.Thereturnvalueisthedeletedvalue.Thekeyvaluemustbegiven.Otherwise,thedefaultvalueisreturned.popitem()

Randomlyreturnsandremovesapairofkeysandvaluesfromthedictionary.2DictionaryKnowledgePoints[Dictionarymethod]Knowledgepoint6Python語言程序設(shè)計(jì)47《字典內(nèi)置函數(shù)》PythonLanguageProgramming48DictionaryBuilt-inFunctions49【字典內(nèi)置函數(shù)】知識(shí)點(diǎn)7函數(shù)及描述實(shí)例len(dict)

計(jì)算字典元素個(gè)數(shù),即鍵的總數(shù)。>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>len(dict)3str(dict)

輸出字典,以可打印的字符串表示。>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>str(dict)"{'Name':'Runoob','Class':'First','Age':7}"type(variable)

返回輸入的變量類型,如果變量是字典就返回字典類型。>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>type(dict)<class

'dict'>2字典知識(shí)要點(diǎn)50[DictionaryBuilt-inFunctions]Knowledgepoint7functionsanddescriptionsInstancelen(dict)

Countsthenumberofdictionaryelements,i.e.,thetotalnumberofkeys.>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>len(dict)3str(dict)

Outputsthedictionaryasaprintablestring.>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>str(dict)"{'Name':'Runoob','Class':'First','Age':7}"type(variable)

Returnsthetypeoftheinputvariable,orthedictionarytypeifthevariableisadictionary.>>>dict=

{'Name':

'Runoob',

'Age':7,

'Class':

'First'}>>>type(dict)<class

'dict'>2DictionaryKnowledgePointsPython語言程序設(shè)計(jì)51《集合的定義+添加集合元素》PythonLanguageProgramming52DefinitionofaCollection+AddingCollectionElements知識(shí)要點(diǎn)53【集合的定義】知識(shí)點(diǎn)1集合:確定的一堆“東西(元素)”,無序的,不重復(fù)的思考:對(duì)比列表?KnowledgePoints54[Definitionofset]Knowledgepoint1Set:adefinitepileof"things(elements)",unordered,non-repeatingThink:Compareandcontrastlists?知識(shí)要點(diǎn)55set1={'張三','李四','王五'}【例】定義一個(gè)簡(jiǎn)單的集合實(shí)例集合注意事項(xiàng):(1)所有元素放在花括號(hào){}里。(2)元素間以逗號(hào)(,)分隔。(3)可以有任意數(shù)量的元素(4)不能有可變?cè)兀ɡ?,列表、集合、字典)【集合的定義】知識(shí)點(diǎn)1【例】定義一個(gè)空集合set1=set()注意:不能使用{}定義空集合,因?yàn)閧}表示空字典KnowledgePoints56Set1={'ZhangSan','LiSi','WangWu'}[Example]DefineasimplecollectioninstancethatAssemblyNotes.(1)Allelementsareplacedincurlybraces{}.(2)Elementsareseparatedbyacomma(,).(3)canhaveanynumberofelements(4)Cannothavemutableelements(e.g.,lists,sets,dictionaries).[Example]Defineanemptysetthatset1=set()Caution.Youcan'tuse{}todefineanemptycollection,Since{}denotestheemptydictionary,the[Definitionofset]Knowledgepoint1知識(shí)要點(diǎn)57【添加集合元素】知識(shí)點(diǎn)2添加集合元素有兩種方式1.使用add方法2.使用update方法123name={'tom','danny'}name.add('smith')print(name){'tom','danny','smith'}【例】使用add(元素值)

添加單個(gè)元素KnowledgePoints58[Addcollectionelement]Knowledgepoint2Therearetwowaystoaddcollectionelements1Usetheaddmethod2.Usetheupdatemethod123name={'tom','danny'}name.add('smith')print(name){'tom','danny','smith'}[Example]Useadd(elementvalue)toaddasingleelement知識(shí)要點(diǎn)59【添加集合元素】知識(shí)點(diǎn)2添加集合元素有兩種方式1.使用add方法2.使用update方法123name={'tom','danny'}name.update(['king','james'])print(name){'king','james','tom','danny'}【例】使用update(任意列表或集合)

添加多個(gè)元素123name={'tom','danny'}name.update(['king','james'],{'kevin','smith'})print(name){'kevin','james','king','smith','tom','danny'}注意:update參數(shù)可以是任意多個(gè)列表或集合KnowledgePoints60Therearetwowaystoaddcollectionelements1Usetheaddmethod2.Usetheupdatemethod123name={'tom','danny'}name.update(['king','james'])print(name){'king','james','tom','danny'}[Example]Useupdate(anylistorset)toaddmultipleelements123name={'tom','danny'}name.update(['king','james'],{'kevin','smith'})print(name){'kevin','james','king','smith','tom','danny'}Caution.Theupdateparametercanbeanynumberoflistsorcollections[Addcollectionelement]Knowledgepoint2Python語言程序設(shè)計(jì)61《刪除集合元素》PythonLanguageProgramming62DeletionofSetElements知識(shí)要點(diǎn)63【刪除集合元素】知識(shí)點(diǎn)3刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

3.使用pop方法4.使用clear方法123name={'king','james','tom','danny'}name.remove('james')print(name){'danny','tom','king'}【例】使用remove(指定元素)

刪除指定元素KnowledgePoints64Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}name.remove('james')print(name){'danny','tom','king'}[Example]Useremovetodeletethespecifiedelement[Deletesetelements]Knowledgepoint3知識(shí)要點(diǎn)65刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

3.使用pop方法4.使用clear方法123name={'king','james','tom','danny'}name.discard('james')print(name){'danny','tom','king'}【例】使用discard(指定元素)

刪除指定元素【刪除集合元素】知識(shí)點(diǎn)3KnowledgePoints66[Deletesetelements]Knowledgepoint3Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}name.discard('james')print(name){'danny','tom','king'}[Example]Usediscardtodeletethespecifiedelement知識(shí)要點(diǎn)67【刪除集合元素】知識(shí)點(diǎn)3刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

3.使用pop方法4.使用clear方法123name={'king','james','tom','danny'}name.remove('mike')print(name)Traceback(mostrecentcalllast):File"test.py",line28,in<module>name.remove('mike')KeyError:'mike'注意:remove(指定元素)使用discard(指定元素)

的區(qū)別區(qū)別:若集合不存在指定元素。remove()會(huì)引發(fā)報(bào)錯(cuò),discard()正常運(yùn)行KnowledgePoints68Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}name.remove('mike')print(name)Traceback(mostrecentcalllast):File"test.py",line28,in<module>name.remove('mike')KeyError:'mike'Note:Thedifferencebetweenremove(specifyingtheelement)anddiscard(specifyingtheelement)Difference:Ifthespecifiedelementdoesnotexistintheset.Remove()willcauseanerror,anddiscard()runsnormally[Deletesetelements]Knowledgepoint3知識(shí)要點(diǎn)69刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

3.使用pop方法4.使用clear方法123name={'king','james','tom','danny'}print(name.pop())#隨機(jī)返回一個(gè)元素print(name)tom{'danny','james','king'}【例】使用pop()

隨機(jī)刪除并返回一個(gè)元素注意:因?yàn)槭请S機(jī)返回所以每次運(yùn)行結(jié)果會(huì)不一樣【刪除集合元素】知識(shí)點(diǎn)3KnowledgePoints70Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}Print(name.pop())#Returnanelementrandomlyprint(name)tom{'danny','james','king'}[Example]Usepop()torandomlydeleteandreturnanelementNote:Sincethereturnisrandomized,thesotheresultswillbedifferentforeachrun[Deletesetelements]Knowledgepoint3知識(shí)要點(diǎn)71刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

3.使用pop方法4.使用clear方法123name={'king','james','tom','danny'}name.clear()print(name)set()【例】使用clear()

清空集合內(nèi)所有元素注意:set()表示空集合【刪除集合元素】知識(shí)點(diǎn)3KnowledgePoints72Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}name.clear()print(name)set()[Example]Clearallelementsinthesetwithclear()Note:set()representsanemptyset[Deletesetelements]Knowledgepoint3Python語言程序設(shè)計(jì)73《訪問集合元素》PythonLanguageProgramming74AccesstoSetElements知識(shí)要點(diǎn)75【訪問集合元素】知識(shí)點(diǎn)4訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

3.使用for循環(huán)12name={'king','james','tom','danny'}print(name[0])Traceback(mostrecentcalllast):File"test.py",line41,in<module>print(name[0])TypeError:'set'objectisnotsubscriptable首先必須注意一點(diǎn):集合是無序的,因此索引也沒有意義。所以無法使用索引或者切片的方式訪問集合元素不可下標(biāo)KnowledgePoints76[Accessingsetelements]Knowledgepoint4Therearethreewaystoaccesscollectionelements 1.Usepopmethod2.Useinoperator

3.Usetheforloop12name={'king','james','tom','danny'}print(name[0])Traceback(mostrecentcalllast):File"test.py",line41,in<module>print(name[0])TypeError:'set'objectisnotsubscriptableFirstofall,itisimportanttonotethatcollectionsareunorderedandthereforeindexesaremeaningless.SoitisnotpossibletoaccesstheelementsofacollectionusingindexesorslicesNobidsmaybeplaced知識(shí)要點(diǎn)77訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

3.使用for循環(huán)123name={'king','james','tom','danny'}print(name.pop())#隨機(jī)返回一個(gè)元素print(name)tom{'danny','james','king'}【例】使用pop()

隨機(jī)刪除并返回一個(gè)元素注意:pop除了隨機(jī)返回一個(gè)元素外,返回的元素也會(huì)被刪除掉【訪問集合元素】知識(shí)點(diǎn)4KnowledgePoints78Therearethreewaystoaccesscollectionelements,the 1.Usepopmethod2.Useinoperator

3.Usetheforloop123name={'king','james','tom','danny'}Print(name.pop())#Returnanelementrandomlyprint(name)tom{'danny','james','king'}[Example]Usepop()torandomlydeleteandreturnanelementNote:Popnotonlyrandomlyreturnsanelement,Thereturnedelementswillalsobedeleted[Accessingsetelements]Knowledgepoint4知識(shí)要點(diǎn)79訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

3.使用for循環(huán)12345name={'king','james','tom','danny'}if'james'inname:print('此元素在集合內(nèi)')else:print('此元素不在集合內(nèi)')此元素在集合內(nèi)【例】使用in

操作符判斷某一個(gè)元素是否在集合內(nèi)注意:notin用于判斷某個(gè)元素是否不在集合內(nèi)【訪問集合元素】知識(shí)點(diǎn)4KnowledgePoints80Therearethreewaystoaccesscollectionelements,the 1.Usepopmethod2.Useinoperator

3.Usetheforloop12345name={'king','james','tom','danny'}if'james'inname:

Print('theelementisinthecollection')else:

Print('Thiselementisnotinthecollection')thiselementisintheset[Example]UsetheinoperatortodeterminewhetheranelementisinthesetNote:notinisusedtojudgewhetheranelementisnotintheset[Accessingsetelements]Knowledgepoint4知識(shí)要點(diǎn)81訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

3.使用for循環(huán)123name={'king','james','tom','danny'}foriinname:print(i)dannykingtomjames【例】使用for

循環(huán)變量訪問所有集合元素【訪問集合元素】知識(shí)點(diǎn)4KnowledgePoints82Therearethreewaystoaccesscollectionelements,the 1.Usepopmethod2.Useinoperator

3.Usetheforloop123name={'king','james','tom','danny'}foriinname:print(i)dannykingtomjames[Example]Usetheforloopvariabletoaccessallsetelements[Accessingsetelements]Knowledgepoint4Python語言程序設(shè)計(jì)83《集合和列表的轉(zhuǎn)化》PythonLanguageProgramming84TransformationofSetsandLists知識(shí)要點(diǎn)85【集合和列表的轉(zhuǎn)化】知識(shí)點(diǎn)5123name_list={'king','james','tom','danny'}name=set(name_list)print(name){'james','king','tom','danny'}【例】使用內(nèi)置函數(shù)set()將列表轉(zhuǎn)化為集合12str_set=set('abcd')print(str_set){'a','d','b','c'}因?yàn)樽址?字符的列表所以本質(zhì)上也是列表轉(zhuǎn)化集合KnowledgePoints86[Transformationofsetsandlists]Knowledgepoint5123name_list={'king','james','tom','danny'}name=set(name_list)print(name){'james','king','tom','danny'}[Example]Usethebuilt-infunctionset()toconvertalisttoaset12str_set=set('abcd')print(str_set){'a','d','b','c'}Sincestring=listofcharactersSoessentiallyit'salsoalistintoacollectionPython語言程序設(shè)計(jì)87《集合的運(yùn)算》PythonLanguageProgramming88OperationsonSets知識(shí)要點(diǎn)89【集合的運(yùn)算】知識(shí)點(diǎn)6四種基本的集合運(yùn)算:子集、并集、交集、差集123456name_1={'king','james',

'tom','danny'}name_2={'tom','danny','smith','kevin'}name_3={'king','james'}print(name_3<name_1)print(name_3<name_2)print(name_3.issubset(name_1))TrueFalseTrue【例】使用<操作符

或者issubset方法進(jìn)行子集運(yùn)算name_1name_3KnowledgePoints90[Operationsonsets]Knowledgepoint6Thefourbasicsetoperations:subset,union,intersection,anddifference123456name_1={'king','james',

'tom','danny'}name_2={'tom','danny','smith','kevin'}name_3={'king','james'}print(name_3<name_1)print(name_3<name_2)print(name_3.issubset(name_1))TrueFalseTrue[Example]Usethe<operatororissubsetmethodtoperformsubsetoperationsname_1name_3知識(shí)要點(diǎn)91【集合的運(yùn)算】

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論