您好,欢迎访问三七文档
当前位置:首页 > 机械/制造/汽车 > 机械/模具设计 > Introduction-to-Python10206
IntroductiontoPythonDataStructures•List•Tuple•DictionaryDataStructures•Construction-Syntax:[elem1,elem2,…]-Heterogeneous,orderedsequence-Mutable-Example:list1=[1,'hello',4+2j,123.12]list1[1,'hello',(4+2j),123.12]list1[0]='a'list1['a','hello',(4+2j),123.12]Lists•Concatenation(+)-Syntax:list1+list2-Example:[1,'a','b']+[3,4,5][1,'a','b',3,4,5]•Repetition(*)-Syntax:list*number-Example:[23,'x']*4[23,'x',23,'x',23,'x',23,'x']Lists-Operations•Indexingoperator:[]•Positiveindicescountfromtheleft•NegativeindicescountfromtherightIndexing0123456-7-6-5-4-3-2-1abcdefgsequence[0]==asequence[-7]==asequence[6]==gsequence[-1]==gsequence[2]==csequence[-5]==c•Twoindicesseparatedbyacolon-Availableforbothstringsandlists-Examplesequence=[0,1,2,3,4,5,6,7]sequence[1:4][1,2,3]sequence[2:-1][2,3,4,5,6]-MissingIndeximpliesendpointsequence[:2][0,1]sequence[3:][3,4,5,6,7]Slices•Immutableversionoflist-Syntax:(elem1,elem2,…)-Itemsintuplecannotbealtered-Example:tuple1=(1,5,10)tuple1[2]=2Traceback(mostrecentcalllast):Filepyshell#136,line1,in?tuple1[2]=2TypeError:objectdoesn'tsupportitemassignmentTuples•Syntax:len(object)-Returnthelengthofobject-Examplelist1=[1,2,3,4,5]len(list1)5string1=lengthofastringlen(string1)18Built-inFunction:len•Mapping-Associateakeywithavalue-EachkeymustbeuniqueDictionarieskeysvalues•Construction-Syntax:{key1:value1,key2:value2…}-Unorderedmap-Example:dict1={'a':1,'b':2}dict1{'a':1,'b':2}dict1['a']1dict1['b']2Dictionaries•Loops-while-Syntax:whilebooleanexpression:body-Executebodyuntilloopingconditionismet-Example:i=0whilei4:printii+=10123ControllingFlow•Loops-for-Syntax:forvarinsequence:body-Executebodyonceforeveryelementinsequence-Example:foriin[0,1,2,3]:printi0123ControllingFlow•Syntax:range([start,]stop[,step])-Generatealistofnumbersfromstarttostopsteppingeverystep-startdefaultsto0,stepdefaultsto1-Examplerange(5)[0,1,2,3,4]range(1,9)[1,2,3,4,5,6,7,8]range(2,20,5)[2,7,12,17]Built-inFunction:range•Usingrangewithfor-Generatelistusedbyforwithrange-Exampleforiinrange(4):printi0123ControllingFlow•Thecontinuestatement-Continuetonextiterationofloop,skippingremainderofbody-Example:forxinrange(8):ifx%2==0:continueprintxControllingFlow1357•Thebreakstatement-Breakoutofinnermostloop-Example:fornumberinrange(10):ifnumber==4:print'Breaking'breakelse:printnumber0123BreakingControllingFlow•Datastructuresalsohavemethods•Usebuilt-infunctiondirtolistallavailablemethods•Examplelst=[1,3,2]dir(lst)['__add__','__class__','__contains__','__delattr__','__delitem__','__delslice__','__doc__','__eq__','__ge__','__getattribute__','__getitem__','__getslice__','__gt__','__hash__','__iadd__','__imul__','__init__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__repr__','__rmul__','__setattr__','__setitem__','__setslice__','__str__','append','count','extend','index','insert','pop','remove','reverse','sort']UsingDataStructures•split-Syntax:string.split([sep])-Returnsalistofstrings-Example:text=12451text.split()['1','2','4','5','1']test=a,b,c,d,etest.split(',')['a','b','c','d','e']Strings-Methods•strip-Syntax:string.strip()-Removeleadingandtrailingwhitespace(tabs,newlines,etc)-Example:padded=stuffpadded.strip()'stuff'padded'stuff'unpadded=padded.strip()unpadded'stuff'Strings-Methods•append-Syntax:list.append(element)-Addelementtoendoflist-Example:list1=[3,'10',2]list1.append('new')list1[3,'10',2,'new']Lists-Methods•pop-Syntax:list.pop([index])-Removeandreturnitematpositionindexfromlist-Defaultistoremovelastitem-Example:list1=[3,'10',2,9,11]list1.pop()11list1[3,'10',2,9]Lists-Methods•insert-Syntax:list.insert(index,element)-Insertelementintolistatpositionindex-Example:list2=[0,1,2,3,4,5]list2.insert(3,'new')list2[0,1,2,'new',3,4,5]Lists-Methods•remove-Syntax:list.remove(element)-Removesthefirstoccurrenceofelementinlist-Example:list2=[0,1,3,4,3,5]list2.remove(3)list2[0,1,4,3,5]Lists-Methods•sort-Syntax:list.sort([cmpfunc])-Sortlistinplace-Example:list3=[4,12,3,9]list3.sort()list3[3,4,9,12]Lists-Methods•reverse-Syntax:list.reverse()-Reverseelementsoflistinplace-Example:list3=[4,12,3,9]list3.reverse()list3[9,3,12,4]Lists-Methods•keys-Syntax:dict.keys()-Returnalistofallthekeysindict-Example:dict1={1:'a',9:'cat',2:[2,1]}dict1.keys()[1,2,9]Dictionaries-Methods•has_key-Syntax:dict.has_key(key)-Determinesifkeyisindict-Example:dict1={'x':1,'y':2}dict1.has_key('x')1dict1.has_key('w')0Dictionaries-Methods•values-Syntax:dict.values()-Returnsalistofallvaluesindict-Example:dict1={(1,2):'a',(3,4):'b',(9,8,7):'c'}dict1.values()['a','c','b']Dictionaries-Methods
本文标题:Introduction-to-Python10206
链接地址:https://www.777doc.com/doc-6364574 .html