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

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Python語言程序設計《字典的定義》PythonLanguageProgrammingDictionaryDefinitions同現實中的字典相似,Python的字典利用”Key-Value”機制對存入字典的數據進行快速查找定位。案例字典的定義Similartothedictionaryinreality,Python'sdictionaryusesthe"KeyValue"mechanismtoquicklysearchandlocatethedatastoredinthedictionary.Casedictionarydefinitions案例字典的定義dict1={'張三':25,'李四':16,'王五':40}d={key1:value1,key2:value2}【例】一個簡單的字典實例字典注意事項:(1)鍵必須是唯一的,但值可以不唯一。(2)值可以取任何數據類型,但鍵必須是不可變的,如字符串、數字或元組。(3)字典的鍵值是“只讀”的,所以不能對鍵和值分別進行初始化。鍵用列表類型可以嗎?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值可以重復嗎?提問可以Question1:Dokeyshavetobeuniqueornon-unique?TheoneandonlyQuestion2:Canthevalueinthedictionaryberepeated?AskaquestionYes,youcan問題3:字典中的鍵用列表類型可以嗎?提問值可以取任何數據類型,但鍵必須是不可變的,如字符串、數字或元組Question3:Isitoktousealisttypeforkeysinadictionary?Thevaluecantakeanydatatype,butthekeymustbeimmutable,suchasastring,number,ortupleAskaquestionPython語言程序設計《訪問字典里的值》PythonLanguageProgrammingAccesstoDictionaryValues案例訪問字典里的值dict={'Name':'DerisWeng','Age':7,'Class':'First'}print("dict['Name']:",dict['Name'])print("dict['Age']:",dict['Age'])訪問字典中的值可以通過dict[Key]的方式,即把相應的鍵放到方括弧[]中進行訪問。【例】通過直接引用訪問字典中的值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'])如果使用字典里沒有對應的鍵,則訪問數據時會報錯。【例】訪問字典中沒有的鍵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問題:根據key得到value的方法有哪幾種?dict[Key]dict.get(Key)提問Question:Whatarethemethodstogetthevalueaccordingtothekey?dict[Key]dict.get(Key)AskaquestionPython語言程序設計《修改字典》PythonLanguageProgrammingModifyingDictionaries案例修改字典dict={'Name':'DerisWeng','Age':7,'Class':'First'}dict['Age']=18;

dict['School']="WZVTC"

print("dict['Age']:",dict['Age'])print("dict['School']:",dict['School'])通過直接引用賦值的方式對字典進行修改【例】修改字典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問題:對字典進行修改時,key在字典中存在與不存在會有什么區別?如果dict[Key]中的Key在字典中不存在,則賦值語句將向字典中添加新內容,即增加新的鍵值對;如果dict[Key]中的Key在字典中存在,則賦值語句將修改字典中的內容。提問Question:Whenmodifyingadictionary,whatisthedifferencebetweentheexistenceandnonexistenceofakeyinthedictionary?Ifthekeyindict[Key]doesnotexistinthedictionary,theassignmentstatementwilladdnewcontenttothedictionary,thatis,addanewkeyvaluepair;Ifthekeyindict[Key]existsinthedictionary,theassignmentstatementwillmodifythecontentinthedictionary.AskaquestionPython語言程序設計《刪除字典元素》PythonLanguageProgrammingDeletingDictionaryElements31可以用del命令刪除單一的元素或者刪除整個字典,也可以用clear清空字典。【例】刪除字典元素dict={'Name':'Runoob','Age':7,'Class':'First'}

deldict[‘Name’]#刪除鍵‘Name’dict.clear()#刪除字典deldict#刪除字典print(“dict[‘Age’]:”,dict[‘Age’])print(“dict[‘School’]:”,dict[‘School’])會發生異常,因為執行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語言程序設計《字典鍵的特性》PythonLanguageProgrammingCharacterizationofDictionaryKeys35兩個重要的點需要記住:【例】重復出現的情況dict={'Name':'DerisWeng','Age':7,'Name':'DerisWeng'}

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

print(“dict[‘Name’]:”,dict[‘Name’])dict[‘Name’]:DerisWeng1)Donotallowthesamekeytoappeartwice.Ifthesamekeyisassignedtwiceduringcreation,thelattervaluewillberemembered.CharacterizationofdictionarykeysCase37兩個重要的點需要記住:【例】不能用列表作為鍵dict={['Name‘]:'DerisWeng','Age':7}

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

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

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

返回一個字典的淺復制dict.fromkeys()

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

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

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

Deleteallelementsinthedictionarydict.copy()

Returnsashallowcopyofadictionarydict.fromkeys()

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

Returnthevalueofthespecifiedkey.Ifthevalueisnotinthedictionary,returnthedefaultvaluekeyindict

Ifthekeyreturnstrueinthedictionarydict,otherwiseitreturnsfalse2DictionaryKnowledgePoints43radiansdict.items()

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

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

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

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

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

Returnsanarrayoftraversable(key,value)tuplesasalistradiansdict.keys()

Returnsallthekeysofadictionaryasalistradiansdict.setdefault(key,default=None)

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

Updatethekey/valuepairofdict2todictradiansdict.values()

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

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

隨機返回并刪除字典中的一對鍵和值。2字典知識要點46pop(key[,default])

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

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

計算字典元素個數,即鍵的總數。>>>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字典知識要點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語言程序設計51《集合的定義+添加集合元素》PythonLanguageProgramming52DefinitionofaCollection+AddingCollectionElements知識要點53【集合的定義】知識點1集合:確定的一堆“東西(元素)”,無序的,不重復的思考:對比列表?KnowledgePoints54[Definitionofset]Knowledgepoint1Set:adefinitepileof"things(elements)",unordered,non-repeatingThink:Compareandcontrastlists?知識要點55set1={'張三','李四','王五'}【例】定義一個簡單的集合實例集合注意事項:(1)所有元素放在花括號{}里。(2)元素間以逗號(,)分隔。(3)可以有任意數量的元素(4)不能有可變元素(例如,列表、集合、字典)【集合的定義】知識點1【例】定義一個空集合set1=set()注意:不能使用{}定義空集合,因為{}表示空字典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知識要點57【添加集合元素】知識點2添加集合元素有兩種方式1.使用add方法2.使用update方法123name={'tom','danny'}name.add('smith')print(name){'tom','danny','smith'}【例】使用add(元素值)

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

添加多個元素123name={'tom','danny'}name.update(['king','james'],{'kevin','smith'})print(name){'kevin','james','king','smith','tom','danny'}注意:update參數可以是任意多個列表或集合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語言程序設計61《刪除集合元素》PythonLanguageProgramming62DeletionofSetElements知識要點63【刪除集合元素】知識點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知識要點65刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

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

刪除指定元素【刪除集合元素】知識點3KnowledgePoints66[Deletesetelements]Knowledgepoint3Therearefourwaystodeleteelementsofacollection,the

1.Usetheremovemethod2.Usethediscardmethod

3.Usepopmethod4.Useclearmethod123name={'king','james','tom','danny'}name.discard('james')print(name){'danny','tom','king'}[Example]Usediscardtodeletethespecifiedelement知識要點67【刪除集合元素】知識點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(指定元素)

的區別區別:若集合不存在指定元素。remove()會引發報錯,discard()正常運行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知識要點69刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

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

隨機刪除并返回一個元素注意:因為是隨機返回所以每次運行結果會不一樣【刪除集合元素】知識點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知識要點71刪除集合元素有四種方式 1.使用remove方法2.使用discard方法

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

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

1.Usetheremovemethod2.Usethediscardmethod

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

3.使用for循環12name={'king','james','tom','danny'}print(name[0])Traceback(mostrecentcalllast):File"test.py",line41,in<module>print(name[0])TypeError:'set'objectisnotsubscriptable首先必須注意一點:集合是無序的,因此索引也沒有意義。所以無法使用索引或者切片的方式訪問集合元素不可下標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知識要點77訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

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

隨機刪除并返回一個元素注意:pop除了隨機返回一個元素外,返回的元素也會被刪除掉【訪問集合元素】知識點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知識要點79訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

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

操作符判斷某一個元素是否在集合內注意:notin用于判斷某個元素是否不在集合內【訪問集合元素】知識點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知識要點81訪問集合元素有三種方式 1.使用pop方法2.使用in操作符

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

循環變量訪問所有集合元素【訪問集合元素】知識點4KnowledgePoints82Therearethreewaystoaccesscollectionelements,the 1.Usepopmethod2.Useinoperator

3.Usetheforloop123name={'king','james','tom','danny'}foriinname:print(i)dannykingtomjames[Example]Usetheforloopvariabletoaccessallsetelements[Accessingsetelements]Knowledgepoint4Python語言程序設計83《集合和列表的轉化》PythonLanguageProgramming84TransformationofSetsandLists知識要點85【集合和列表的轉化】知識點5123name_list={'king','james','tom','danny'}name=set(name_list)print(name){'james','king','tom','danny'}【例】使用內置函數set()將列表轉化為集合12str_set=set('abcd')print(str_set){'a','d','b','c'}因為字符串=字符的列表所以本質上也是列表轉化集合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語言程序設計87《集合的運算》PythonLanguageProgramming88OperationsonSets知識要點89【集合的運算】知識點6四種基本的集合運算:子集、并集、交集、差集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方法進行子集運算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知識要點91【集合的運算】

溫馨提示

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

評論

0/150

提交評論