




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
IntroductiontoComputerProgrammingSchoolofComputerandInformationScienceSouthwestForestryUniversity2014.9計(jì)算機(jī)編程導(dǎo)論
西南林業(yè)大學(xué)計(jì)算機(jī)與信息學(xué)院2014.3ReviewChapter2Using
ArrayArraysQuestion2-1、2-2、2-3ListDefinition:[,] Create:=Read: ListName[index]Slices: ListName[index1:index2]Adding: “+”,append(),extend(),insert()Search: count(),in,index()Delete: del,remove(),pop()Function:cmp(),len(),max(),min(),sorted(),reversed(),sum()復(fù)習(xí)第2章表格處理表格問題2-1、2-2列表定義創(chuàng)建讀取切片添加刪除函數(shù)2.4TupleAtupleisacompounddatatype.Itissimilartoalistexceptthatitisimmutable.Likelist,atupleisacomma-separatedlistofvalues.But
tuple’s
eIements
in
“()”.Forexample:(10,20,30,40)
('crunchyfrog','rambladder','larkvomit')2.4元組元組和列表類似,但其元素是不可變的,元組一旦創(chuàng)建,用任何方法都不可以修改其元素。元組的定義方式和列表相同,但定義時(shí)所有元素是放在一對圓括號“(”和“)”中,而不是方括號中。下面這些都是合法的元組:(10,20,30,40) ('crunchyfrog','rambladder','larkvomit')2.4TupleOperations(1)CreatetupleUsethe“=”toassignatupletoavariable.>>>a_tuple=('a',)>>>a_tuple('a‘,)>>>a_tuple=('a','b','mpilgrim','z','example')>>>a_tuple('a','b','mpilgrim','z','example')fNote:Withoutthecomma,Pythontreats(’a’)asastringinparentheses2.4元組(1)創(chuàng)建元組使用“=”將一個(gè)元組賦值給變量。例如:>>>a_tuple=('a',)>>>a_tuple('a')>>>a_tuple=('a','b','mpilgrim','z','example')>>>a_tuple('a','b','mpilgrim','z','example')注意:如不加逗號,(‘a(chǎn)’)會被認(rèn)為是放在括號中的字符串2.4TupleOperations(2)ReadelementsTheoperationsontuplesarethesameaslists.>>>a_tuple[2]'mpilgrim'>>>a_tuple[-1]'example'>>>a_tuple[-5]'a'>>>a_tuple[-7]Traceback(mostrecentcalllast):File"<pyshell#68>",line1,in<module>a_tuple[-7]IndexError:tupleindexoutofrange>>>a_tuple[5]Traceback(mostrecentcalllast):File"<pyshell#69>",line1,in<module>a_tuple[5]IndexError:tupleindexoutofrangea_tuple=('a','b','mpilgrim','z','example')2.4元組(2)讀取元素用變量名加元素序號(放中括號中)即可訪問元組中某個(gè)元素同列表相同,元組的元素都有固定的順序,第一個(gè)元素序號也為0,合法的元組元素序號的規(guī)定與列表相同。例如:>>>a_tuple[2]'mpilgrim'>>>a_tuple[-1]'example'>>>a_tuple[-5]'a'>>>a_tuple[-7]Traceback(mostrecentcalllast):File"<pyshell#68>",line1,in<module>a_tuple[-7]IndexError:tupleindexoutofrange>>>a_tuple[5]Traceback(mostrecentcalllast):File"<pyshell#69>",line1,in<module>a_tuple[5]IndexError:tupleindexoutofrangea_tuple=('a','b','mpilgrim','z','example')2.4TupleOperations(3)SliceThesliceoperatorselectsarangeofelements
from
a
tuple:>>>a_tuple[1:3]('b','mpilgrim')a_tuple=('a','b','mpilgrim','z','example')2.4元組(3)元組切片與列表一樣,元組也可以進(jìn)行切片操作對列表切片可以得到新的列表;對元組切片可以得到新的元組。例如:>>>a_tuple[1:3]('b','mpilgrim')a_tuple=('a','b','mpilgrim','z','example')2.4TupleOperations(4)SearchUsecount()methodtocalculatethenumberofelementsinatuple:>>>a_tuple.count('b')1Use“in”tocheckwhetheranelementisinatuple:>>>'ab'ina_tupleFalse>>>'z'ina_tupleTrueUsetheindex()methodtoreturntheexactlocationofanelementinthetuple:>>>a_tuple.index('z')3>>>a_tuple.index(5)Traceback(mostrecentcalllast):File"<pyshell#78>",line1,in<module>a_tuple.index(5)ValueError:tuple.index(x):xnotintuplea_tuple=('a','b','mpilgrim','z','example')2.4元組(4)檢索元素使用count()方法計(jì)算元組中某個(gè)元素出現(xiàn)的次數(shù);例如:>>>a_tuple.count('b')1使用in運(yùn)算符返回某個(gè)元素是否在該元組中;例如:>>>'ab'ina_tupleFalse>>>'z'ina_tupleTrue使用index()方法返回某個(gè)元素在元組中的準(zhǔn)確位置;例如:>>>a_tuple.index('z')3>>>a_tuple.index(5)Traceback(mostrecentcalllast):File"<pyshell#78>",line1,in<module>a_tuple.index(5)ValueError:tuple.index(x):xnotintuplea_tuple=('a','b','mpilgrim','z','example')2.4TupleandListDifferencesandConversionAtuplecannotbechangedinanywayonceitiscreated.Noappend()orextend()methodfortuples.Youcannotaddelementstothetuple.Noremove()orpop()methodfortuplestoo.Tuplesadvantages:FasterSaferCanbeusedfordictionarykeysTuplescanbeconvertedintolists,andvice-versa.tuple()function:listtuplelist()function:tuplelistf2.4元組元組和列表的區(qū)別和轉(zhuǎn)換元組中的數(shù)據(jù)一旦定義就不允許更改。因此,元組沒有append()或extend()方法,無法向元組中添加元素;元組沒有remove()或pop()方法,不能從元組中刪除元素。元組與列表相比有下列優(yōu)點(diǎn):元組的速度比列表更快。如果定義了一系列常量值,而所需做的僅是對它進(jìn)行遍歷,那么一般使用元組而不用列表。元組對不需要改變的數(shù)據(jù)進(jìn)行“寫保護(hù)”將使得代碼更加安全。一些元組可用作字典鍵(特別是包含字符串、數(shù)值和其它元組這樣的不可變數(shù)據(jù)的元組)。列表永遠(yuǎn)不能當(dāng)做字典鍵使用,因?yàn)榱斜聿皇遣豢勺兊摹TM可轉(zhuǎn)換成列表,反之亦然。內(nèi)建的tuple()函數(shù)接受一個(gè)列表參數(shù),并返回一個(gè)包含同樣元素的元組,而list()函數(shù)接受一個(gè)元組參數(shù)并返回一個(gè)列表。從效果上看,tuple()凍結(jié)列表,而list()融化元組。2.4TupleOperationsTupleassignmentofmultiplevariables:>>>v_tuple=(False,3.5,'exp')>>>(x,y,z)=v_tuple>>>xFalse>>>y3.5>>>z'exp’a2.4元組可以利用元組來一次性的對多個(gè)變量賦值。例如:>>>v_tuple=(False,3.5,'exp')>>>(x,y,z)=v_tuple>>>xFalse>>>y3.5>>>z'exp'2.5Dictionary1.DefinitionThedictionaryisanunorderedsetofkey-valuepairs.Eachelementcontainstwoparts:thekeysandvalues.Whenyouaddakeytoadictionary,youmustalsoaddavalueforthatkey.2.Dictionaryoperations(1)CreateTheelementsofadictionaryappearasacomma-separatedlist.Eachelementcontainsankeyandavalueseparatedbyacolon“{}”.>>>a_dict={'server':'','database':'mysql'}>>>a_dict{'database':'mysql','server':''}a2.5字典1.字典定義字典是鍵值對的無序集合。字典中的每個(gè)元素包含兩部分:鍵和值,向字典添加一個(gè)鍵的同時(shí),必須為該鍵增添一個(gè)值。2.字典的常用操作(1)創(chuàng)建字典定義字典時(shí),每個(gè)元素的鍵和值用冒號分隔,元素之間用逗號分隔,所有的元素放在一對大括號“{”和“}”中。例如:>>>a_dict={'server':'','database':'mysql'}>>>a_dict{'database':'mysql','server':''}2.5DictionaryOperations(2)SearchWecanusethekeysofthedictionarytolookupthevaluesInturn,maynot>>>a_dict['server']''>>>a_dict['database']'mysql'>>>a_dict['']Traceback(mostrecentcalllast):File"<pyshell#85>",line1,in<module>a_dict['']KeyError:'’aa_dict={'database':'mysql','server':''}2.5字典(2)查找值字典定義后,可以通過鍵來查找值,反之則不允許。例如:>>>a_dict['server']''>>>a_dict['database']'mysql'>>>a_dict['']Traceback(mostrecentcalllast):File"<pyshell#85>",line1,in<module>a_dict['']KeyError:''a_dict={'database':'mysql','server':''}2.5DictionaryOperations(3)TraversalUseloopstatementtotraversethekeysandvaluesofeachelementinthedictionary>>>forkeyina_dict.keys():print(key,a_dict[key])databasemysqlserverfa_dict={'database':'mysql','server':''}2.5字典(3)遍歷字典可以用循環(huán)語句來遍歷字典中每個(gè)元素的鍵和值。例如:>>>forkeyina_dict.keys():print
key,a_dict[key]databasemysqlservera_dict={'database':'mysql','server':''}2.5字典(3)遍歷字典可以用循環(huán)語句來遍歷字典中每個(gè)元素的鍵。例如:>>>forkeyina_dict.keys():print
keyserverdatabasea_dict={'database':'mysql','server':''}2.5字典(3)遍歷字典可以用循環(huán)語句來遍歷字典中每個(gè)元素的值。例如:>>>forkeyina_dict.keys():print
a_dict[key]mysql>>>forvina_dict.values():
printvmysqla_dict={'database':'mysql','server':''}2.5DictionaryOperations(4)AddingandModifyDictionarieshavenosizelimit.Wecanaddtothedictionarykey-valuepairs,ormodifythevalue.Addormodifyoperate:variablename[key]=value.Forexample>>>a_dict['user']='mark'>>>a_dict{'database':'mysql','server':'','user':'mark'}>>>a_dict['database']='blog'>>>a_dict{'database':'blog','server':'','user':'mark'}fa_dict={'database':'mysql','server':''}2.5字典(4)添加和修改字典字典沒有預(yù)定義的大小限制??梢噪S時(shí)向字典中添加新的鍵值對,或者修改現(xiàn)有鍵所關(guān)聯(lián)的值添加和修改的方法相同,都是使用“字典變量名[鍵名]=鍵值”的形式,區(qū)分究竟是添加還是修改是看鍵名與字典中現(xiàn)有的鍵名是否重復(fù),因?yàn)樽值渲胁辉试S有重復(fù)的鍵。如不重復(fù)則是添加新健值對,如重復(fù)則是將該鍵對應(yīng)的值修改為新值。例如:>>>a_dict['user']='mark'>>>a_dict{'database':'mysql','server':'','user':'mark'}>>>a_dict['database']='blog'>>>a_dict{'database':'blog','server':'','user':'mark'}a_dict={'database':'mysql','server':''}2.5DictionaryOperations(5)LengthLikelistsandtuples,wecanusethelen()functiontogetthenumberofdictionary’elements.>>>len(a_dict)3(6)SearchWecanuse"in"totestwhetheraparticularkeyisinthedictionary.>>>'server'ina_dictTrue>>>'mysql'ina_dictFalsefa_dict=
{'database':'blog','server':'','user':'mark'}2.5字典(5)字典長度與列表、元組類似,可以用len()函數(shù)返回字典中鍵的數(shù)量。例如:>>>len(a_dict)3(6)字典檢索可以使用in運(yùn)行符來測試某個(gè)特定的鍵是否在字典中。例如:>>>'server'ina_dictTrue>>>'mysql'ina_dictFalsea_dict=
{'database':'blog','server':'','user':'mark'}2.5DictionaryOperations(7)DeleteDelstatementtoremoveakeyanditsvalue,ortheentiredictionaryClear()methodtodeletealltheelementsinthedictionaryPop()methodtoremoveandreturnthespecifiedkeyelements.>>>dela_dict['server']>>>a_dict{'database':'blog','user':'mark'}>>>a_dict.pop('database')'blog'>>>a_dict{'user':'mark'}>>>a_dict.clear()>>>a_dict{}>>>dela_dict>>>a_dictTraceback(mostrecentcalllast):File"<pyshell#103>",line1,in<module>a_dictNameError:name'a_dict'isnotdefineda_dict=
{'database':'blog','server':'','user':'mark'}2.5字典(7)刪除元素和字典可以使用del語句刪除指定鍵的元素或整個(gè)字典使用clear()方法來刪除字典中所有元素使用pop()方法刪除并返回指定鍵的元素。例如dela_dict[‘server’]將刪除鍵值為‘server’的元素a_dict.pop(‘database’)將刪除并返回健為‘database’的元素a_dict.clear()將刪除字典中所有元素,dela_dict將刪除整個(gè)字典。>>>dela_dict['server']>>>a_dict{'database':'blog','user':'mark'}>>>a_dict.pop('database')'blog'>>>a_dict{'user':'mark'}>>>a_dict.clear()>>>a_dict{}>>>dela_dict>>>a_dictTraceback(mostrecentcalllast):File"<pyshell#103>",line1,in<module>a_dictNameError:name'a_dict'isnotdefineda_dict=
{'database':'blog','server':'','user':'mark'}2.6Theapplicationofarray【EG2-1】ScorestatisticsDescription:Given10scores,pleasefindoutthenumberofpersonsineachlevel.Thefourlevelsareexcellent(100to90),good(89to80),medium(79to60),andpoor(59to0).Analysis:thescoresarestoredinalist.Fourvariablesaredefinedandinitializedto0tostorethenumberofpersonsineachofthefourlevels.Eachscoreischeckedtoseewhichlevelitbelongsto.Andincreasethevalueofthevariablecorrespondingtothatlevelby1.2.6序列應(yīng)用【例2-1】成績統(tǒng)計(jì)問題問題描述:已知10個(gè)成績,請對其進(jìn)行統(tǒng)計(jì),輸出優(yōu)(100~90)、良(89~80)、中(79~60)、差(59~0)四個(gè)等級的人數(shù)。分析:將成績存放在列表中。預(yù)設(shè)四個(gè)變量并初始化為0,用來存放四個(gè)等級的人數(shù)。對每個(gè)成績進(jìn)行判斷,屬哪個(gè)等級范圍就將對應(yīng)變量值加1。2.6序列應(yīng)用開始定義a、b、c、d四個(gè)變量并全部初始化為0,它們分別對應(yīng)優(yōu)、良、中、差四個(gè)等級的人數(shù)將10個(gè)成績存放在列表score中輸出a、b、c、d四個(gè)統(tǒng)計(jì)結(jié)果結(jié)束對score中每個(gè)成績進(jìn)行判斷,是哪個(gè)等級則對應(yīng)變量自加1圖2-3成績統(tǒng)計(jì)流程圖2.6序列應(yīng)用程序:#scorecount:Exp2_1.pyscore=[68,75,32,99,78,45,88,72,83,78]a=0b=0c=0d=0#輸出所有成績print"成績分別為:",forsinscore:
prints,#換行print#對成績進(jìn)行分段統(tǒng)計(jì)forsinscore:
ifs<60:
d=d+1
elifs<80:
c=c+1
elifs<90:
b=b+1
else:
a=a+1print"分段統(tǒng)計(jì)結(jié)果:優(yōu)",a,"人,良",b,"人,中",c,"人,差",d,"人"程序運(yùn)行結(jié)果:成績分別為:68753299784588728378分段統(tǒng)計(jì)結(jié)果:優(yōu)1人,良2人,中5人,差2人2.6Theapplicationofarray【EG2-2】ScoressortDescription:
Givennamesandscoresof10students,pleasefindoutthehighestandlowestscoresandnames,outputtheaveragescoreofall10students.Analysis:
Storethestudents'namesandscoresinadictionary.Initializethevariablestoringthehighestscoreto0,andthelowestscorevariableisinitializedto100.Eachkeyinthedictionaryiscomparedwiththecurrenthighestscore,thehighestscorevariableisupdatedwheneverahigherscoreisfound;Andalsothekeyiscomparedwiththecurrentminimumscore,thelowestscorevariablegetsupdatedwheneveralowervalueisfound.Atthesametime,thesumofscoresiscumulated.Finally,theaveragescoreiscalculated.2.6序列應(yīng)用【例2-2】成績排序問題問題描述:已知10個(gè)學(xué)生的姓名和成績,請找出其中的最高分和最低分,并求出全班同學(xué)的平均分。分析:將學(xué)生姓名和成績以健值對形式存放在一個(gè)字典中。初始化存放最高分的變量為0,存放最低分的變量為100。取出字典中每個(gè)鍵值對,拿其值與目前的最高分比較,若大于最高分,則更新最高分;與目前的最低分比較,若小于最低分,則更新最低分。同時(shí)累加成績。最后,算出平均分。2.6序列應(yīng)用開始定義maxscore、maxstudname用來存放最高分及其姓名;定義minscore、minstudname用來存放最低分及其姓名;定義avrscore存放平均成績,求出學(xué)生人數(shù)放在studnum中將10個(gè)姓名和成績放在字典中輸出結(jié)果結(jié)束循環(huán)對字典中每個(gè)成績與目前的最高分、最低分進(jìn)行比較:若高于最高分則更新最高分及姓名,若低于最低分則更新最低分及姓名將成績累加到變量avrscore中用avrscore(總成績)除以studnum得到平均分放回avrscore中圖2-4成績排序流程圖2.6序列應(yīng)用程序:#scoresort:Exp2_2.pystudscore={"唐僧":45,"孫悟空":78,"豬八戒":40,"沙僧":96,"如來":65,"觀音":90,"白骨精":78,"紅孩兒":99,"太上老君":60,"白龍馬":87}maxscore=0maxstudname=''minscore=100minstudname=''avrscore=0studnum=len(studscore)#輸出所有成績:print"成績分別為:"forkeyinstudscore.keys():
printkey,studscore[key],";",#換行print2.6序列應(yīng)用#進(jìn)行成績統(tǒng)計(jì)forkeyinstudscore.keys():ifstudscore[key]>maxscore:maxscore=studscore[key]maxstudname=keyifstuds
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年海東貨運(yùn)考試題庫
- 入圍中標(biāo)合同范本
- 公司注冊協(xié)議合同范本
- 公司家具搬遷合同范本
- 公路防撞墻勞務(wù)合同范本
- 公司合同股合同范本
- 保潔服裝購置合同范本
- UI軟件合同范本
- 正規(guī)家具合同范本
- 鄉(xiāng)政府廚師合同范本
- 部編版四年級語文下冊27《巨人的花園》PPT課件(共2課時(shí))
- 測繪項(xiàng)目收費(fèi)標(biāo)準(zhǔn)2009
- 新人教版六年級下冊科學(xué)全冊教學(xué)設(shè)計(jì)教案
- 《成本會計(jì)學(xué)》習(xí)題集及答案
- 社區(qū)醫(yī)院建設(shè)標(biāo)準(zhǔn)
- 個(gè)人所得稅稅率表【自動提取稅率計(jì)算】
- 浙美版小學(xué)美術(shù)五年級下冊課件1畫家故居
- 中國作家協(xié)會入會申請表
- 熒光綠送貨單樣本excel模板
- 科技館解說詞
- 水土保持治理效益計(jì)算
評論
0/150
提交評論