Python程序設(shè)計(jì)-第2章-使用序列-2(第4次課).ppt_第1頁(yè)
Python程序設(shè)計(jì)-第2章-使用序列-2(第4次課).ppt_第2頁(yè)
Python程序設(shè)計(jì)-第2章-使用序列-2(第4次課).ppt_第3頁(yè)
Python程序設(shè)計(jì)-第2章-使用序列-2(第4次課).ppt_第4頁(yè)
Python程序設(shè)計(jì)-第2章-使用序列-2(第4次課).ppt_第5頁(yè)
已閱讀5頁(yè),還剩43頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、Introduction to Computer Programming,School of Computer and Information Science Southwest Forestry University 2014.9,計(jì)算機(jī)編程導(dǎo)論,西南林業(yè)大學(xué) 計(jì)算機(jī)與信息學(xué)院 2014.3,Review,Chapter 2 Using Array Arrays Question 2-1、2-2、2-3 List Definition: , Create: = Read: ListNameindex Slices: ListNameindex1:index2 Adding: “+”, app

2、end(), extend(), insert() Search: count(), in, index() Delete: del, remove(), pop() Function: cmp( ),len( ),max( ),min( ),sorted( ),reversed( ),sum( ),復(fù)習(xí),第2章 表格處理 表格問(wèn)題2-1、2-2 列表 定義 創(chuàng)建 讀取 切片 添加 刪除 函數(shù),2.4 Tuple,A tuple is a compound data type. It is similar to a list except that it is immutable. Like

3、list, a tuple is a comma-separated list of values. But tuples eIements in “( )”. For example: (10, 20, 30, 40) (crunchy frog, ram bladder, lark vomit),2.4 元組,元組和列表類(lèi)似,但其元素是不可變的,元組一旦創(chuàng)建,用任何方法都不可以修改其元素。 元組的定義方式和列表相同,但定義時(shí)所有元素是放在一對(duì)圓括號(hào)“(”和“)”中,而不是方括號(hào)中。 下面這些都是合法的元組: (10, 20, 30, 40) (crunchy frog, ram bladd

4、er, lark vomit),2.4 Tuple Operations,(1)Create tuple Use the “=” to assign a tuple to a variable. a_tuple = (a, ) a_tuple (a,) a_tuple = (a, b, mpilgrim, z, example) a_tuple (a, b, mpilgrim, z, example) f,Note: Without the comma, Python treats (a) as a string in parentheses,2.4 元組,(1)創(chuàng)建元組 使用“=”將一個(gè)元組

5、賦值給變量。 例如: a_tuple = (a, ) a_tuple (a) a_tuple = (a, b, mpilgrim, z, example) a_tuple (a, b, mpilgrim, z, example),注意:如不加逗號(hào),(a)會(huì)被 認(rèn)為是放在括號(hào)中的字符串,2.4 Tuple Operations,(2)Read elements The operations on tuples are the same as lists., a_tuple2 mpilgrim a_tuple-1 example a_tuple-5 a a_tuple-7 Traceback (m

6、ost recent call last): File , line 1, in a_tuple-7 IndexError: tuple index out of range a_tuple5 Traceback (most recent call last): File , line 1, in a_tuple5 IndexError: tuple index out of range,a_tuple=(a, b, mpilgrim, z, example),2.4 元組,(2)讀取元素 用變量名加元素序號(hào)(放中括號(hào)中)即可訪問(wèn)元組中某個(gè)元素 同列表相同,元組的元素都有固定的順序,第一個(gè)元素

7、序號(hào)也為0,合法的元組元素序號(hào)的規(guī)定與列表相同。 例如:, a_tuple2 mpilgrim a_tuple-1 example a_tuple-5 a a_tuple-7 Traceback (most recent call last): File , line 1, in a_tuple-7 IndexError: tuple index out of range a_tuple5 Traceback (most recent call last): File , line 1, in a_tuple5 IndexError: tuple index out of range,a_tu

8、ple=(a, b, mpilgrim, z, example),2.4 Tuple Operations,(3)Slice The slice operator selects a range of elements from a tuple: a_tuple1:3 (b, mpilgrim),a_tuple=(a, b, mpilgrim, z, example),2.4 元組,(3)元組切片 與列表一樣,元組也可以進(jìn)行切片操作 對(duì)列表切片可以得到新的列表;對(duì)元組切片可以得到新的元組。 例如: a_tuple1:3 (b, mpilgrim),a_tuple=(a, b, mpilgrim

9、, z, example),2.4 Tuple Operations,(4)Search Use count() method to calculate the number of elements in a tuple: a_tuple.count(b) 1 Use “in” to check whether an element is in a tuple: ab in a_tuple False z in a_tuple True,Use the index( ) method to return the exact location of an element in the tuple

10、: a_tuple.index(z) 3 a_tuple.index(5) Traceback (most recent call last): File , line 1, in a_tuple.index(5) ValueError: tuple.index(x): x not in tuple,a_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 in a_tuple False

11、z in a_tuple True,使用index( )方法返回某個(gè)元素在元組中的準(zhǔn)確位置; 例如: a_tuple.index(z) 3 a_tuple.index(5) Traceback (most recent call last): File , line 1, in a_tuple.index(5) ValueError: tuple.index(x): x not in tuple,a_tuple=(a, b, mpilgrim, z, example),2.4 Tuple and List,Differences and Conversion A tuple can not b

12、e changed in any way once it is created. No append () or extend () method for tuples. You can not add elements to the tuple. No remove () or pop () method for tuples too. Tuples advantages: Faster Safer Can be used for dictionary keys Tuples can be converted into lists, and vice-versa. tuple () func

13、tion: list tuple list () function: tuple list f,2.4 元組,元組和列表的區(qū)別和轉(zhuǎn)換 元組中的數(shù)據(jù)一旦定義就不允許更改。因此,元組沒(méi)有append( )或extend( )方法,無(wú)法向元組中添加元素;元組沒(méi)有remove( )或pop( )方法,不能從元組中刪除元素。 元組與列表相比有下列優(yōu)點(diǎn): 元組的速度比列表更快。如果定義了一系列常量值,而所需做的僅是對(duì)它進(jìn)行遍歷,那么一般使用元組而不用列表。 元組對(duì)不需要改變的數(shù)據(jù)進(jìn)行“寫(xiě)保護(hù)”將使得代碼更加安全。 一些元組可用作字典鍵(特別是包含字符串、數(shù)值和其它元組這樣的不可變數(shù)據(jù)的元組)。列表永遠(yuǎn)不能

14、當(dāng)做字典鍵使用,因?yàn)榱斜聿皇遣豢勺兊摹?元組可轉(zhuǎn)換成列表,反之亦然。內(nèi)建的tuple( )函數(shù)接受一個(gè)列表參數(shù),并返回一個(gè)包含同樣元素的元組,而list( )函數(shù)接受一個(gè)元組參數(shù)并返回一個(gè)列表。從效果上看,tuple( )凍結(jié)列表,而list( )融化元組。,2.4 Tuple Operations,Tuple assignment of multiple variables: v_tuple = (False, 3.5, exp) (x, y, z) = v_tuple x False y 3.5 z exp a,2.4 元組,可以利用元組來(lái)一次性的對(duì)多個(gè)變量賦值。例如: v_tuple =

15、 (False, 3.5, exp) (x, y, z) = v_tuple x False y 3.5 z exp,2.5 Dictionary,1. Definition The dictionary is an unordered set of key-value pairs. Each element contains two parts: the keys and values. When you add a key to a dictionary, you must also add a value for that key. 2. Dictionary operations (1

16、)Create The elements of a dictionary appear as a comma-separated list. Each element contains an key and a value separated by a colon“”. a_dict = server: , database: mysql a_dict database: mysql, server: a,2.5 字典,1. 字典定義 字典是鍵值對(duì)的無(wú)序集合。 字典中的每個(gè)元素包含兩部分:鍵和值,向字典添

17、加一個(gè)鍵的同時(shí),必須為該鍵增添一個(gè)值。 2. 字典的常用操作 (1)創(chuàng)建字典 定義字典時(shí),每個(gè)元素的鍵和值用冒號(hào)分隔,元素之間用逗號(hào)分隔,所有的元素放在一對(duì)大括號(hào)“”和“”中。 例如: a_dict = server: , database: mysql a_dict database: mysql, server: ,2.5 Dictionary Operations,(2)Search We can use the keys of the dictionary to look up the values

18、 In turn, may not a_dictserver a_dictdatabase mysql a_ Traceback (most recent call last): File , line 1, in a_ KeyError: a,a_dict=database: mysql, server: ,2.5 字典,(2)查找值 字典定義后,可以通過(guò)

19、鍵來(lái)查找值,反之則不允許。 例如: a_dictserver a_dictdatabase mysql a_ Traceback (most recent call last): File , line 1, in a_ KeyError: ,a_dict=database: mysql, server: ,2.5 Dictionary Operations,

20、(3)Traversal Use loop statement to traverse the keys and values of each element in the dictionary for key in a_dict.keys(): print(key, a_dictkey) database mysql server f,a_dict=database: mysql, server: ,2.5 字典,(3)遍歷字典 可以用循環(huán)語(yǔ)句來(lái)遍歷字典中每個(gè)元素的鍵和值。 例如: for key in

21、 a_dict.keys(): print key, a_dictkey database mysql server ,a_dict=database: mysql, server: ,2.5 字典,(3)遍歷字典 可以用循環(huán)語(yǔ)句來(lái)遍歷字典中每個(gè)元素的鍵。 例如: for key in a_dict.keys(): print key server database,a_dict=database: mysql, server: ,2.5 字典,(3)遍歷字典 可

22、以用循環(huán)語(yǔ)句來(lái)遍歷字典中每個(gè)元素的值。 例如: for key in a_dict.keys(): print a_dictkey mysql for v in a_dict.values(): print v mysql,a_dict=database: mysql, server: ,2.5 Dictionary Operations,(4)Adding and Modify Dictionaries have no size limit. We can

23、add to the dictionary key-value pairs, or modify the value. Add or modify operate: variable name key = value. For example a_dictuser = mark a_dict database: mysql, server: , user: mark a_dictdatabase=blog a_dict database: blog, server: , user: mark f,a_dic

24、t=database: mysql, server: ,2.5 字典,(4)添加和修改字典 字典沒(méi)有預(yù)定義的大小限制。 可以隨時(shí)向字典中添加新的鍵值對(duì),或者修改現(xiàn)有鍵所關(guān)聯(lián)的值 添加和修改的方法相同,都是使用“字典變量名鍵名=鍵值”的形式,區(qū)分究竟是添加還是修改是看鍵名與字典中現(xiàn)有的鍵名是否重復(fù),因?yàn)樽值渲胁辉试S有重復(fù)的鍵。如不重復(fù)則是添加新健值對(duì),如重復(fù)則是將該鍵對(duì)應(yīng)的值修改為新值。 例如: a_dictuser = mark a_dict database: mysql, server: , user:

25、 mark a_dictdatabase=blog a_dict database: blog, server: , user: mark,a_dict=database: mysql, server: ,2.5 Dictionary Operations,(5)Length Like lists and tuples, we can use the len () function to get the number of dictionaryelements. len(a_dict) 3 (6)Searc

26、h We can use in to test whether a particular key is in the dictionary. server in a_dict True mysql in a_dict False f,a_dict= database: blog, server: , user: mark,2.5 字典,(5)字典長(zhǎng)度 與列表、元組類(lèi)似,可以用len( )函數(shù)返回字典中鍵的數(shù)量。 例如: len(a_dict) 3 (6)字典檢索 可以使用in運(yùn)行符來(lái)測(cè)試某個(gè)特定的鍵是否在字典中。 例如: server in a_di

27、ct True mysql in a_dict False,a_dict= database: blog, server: , user: mark,2.5 Dictionary Operations,(7)Delete Del statement to remove a key and its value, or the entire dictionary Clear () method to delete all the elements in the dictionary Pop () method to remove and return t

28、he specified key elements., del a_dictserver a_dict database: blog, user: mark a_dict.pop(database) blog a_dict user: mark a_dict.clear( ) a_dict del a_dict a_dict Traceback (most recent call last): File , line 1, in a_dict NameError: name a_dict is not defined,a_dict= database: blog, server: db.div

29、, user: mark,2.5 字典,(7)刪除元素和字典 可以使用del語(yǔ)句刪除指定鍵的元素或整個(gè)字典 使用clear( )方法來(lái)刪除字典中所有元素 使用pop ()方法刪除并返回指定鍵的元素。 例如 del a_dictserver將刪除鍵值為server的元素 a_dict.pop(database)將刪除并返回健為database的元素 a_dict.clear()將刪除字典中所有元素,del a_dict將刪除整個(gè)字典。, del a_dictserver a_dict database: blog, user: mark a_dict.pop(da

30、tabase) blog a_dict user: mark a_dict.clear( ) a_dict del a_dict a_dict Traceback (most recent call last): File , line 1, in a_dict NameError: name a_dict is not defined,a_dict= database: blog, server: , user: mark,2.6 The application of array,【EG2-1】Score statistics Descriptio

31、n: Given 10 scores, please find out the number of persons in each level. The four levels are excellent (100 to 90), good (89 to 80), medium (79 to 60), and poor (59 to 0). Analysis: the scores are stored in a list. Four variables are defined and initialized to 0 to store the number of persons in eac

32、h of the four levels. Each score is checked to see which level it belongs to. And increase the value of the variable corresponding to that level by 1.,2.6 序列應(yīng)用,【例2-1】 成績(jī)統(tǒng)計(jì)問(wèn)題 問(wèn)題描述:已知10個(gè)成績(jī),請(qǐng)對(duì)其進(jìn)行統(tǒng)計(jì),輸出優(yōu)(10090)、良(8980)、中(7960)、差(590)四個(gè)等級(jí)的人數(shù)。 分 析:將成績(jī)存放在列表中。預(yù)設(shè)四個(gè)變量并初始化為0,用來(lái)存放四個(gè)等級(jí)的人數(shù)。對(duì)每個(gè)成績(jī)進(jìn)行判斷,屬哪個(gè)等級(jí)范圍就將對(duì)應(yīng)變量值

33、加1。,2.6 序列應(yīng)用,2.6 序列應(yīng)用,程序: #score count:Exp2_1.py score=68, 75, 32, 99, 78, 45, 88, 72, 83, 78 a = 0 b = 0 c = 0 d = 0 #輸出所有成績(jī) print 成績(jī)分別為:, for s in score: print s, #換行 print,#對(duì)成績(jī)進(jìn)行分段統(tǒng)計(jì) for s in score: if s 60: d = d + 1 elif s 80: c = c + 1 elif s 90: b = b + 1 else: a = a + 1 print 分段統(tǒng)計(jì)結(jié)果:優(yōu),a,人,良,

34、b,人,中,c,人,差,d,人,程序運(yùn)行結(jié)果: 成績(jī)分別為: 68 75 32 99 78 45 88 72 83 78 分段統(tǒng)計(jì)結(jié)果:優(yōu) 1 人,良 2 人,中 5 人,差 2 人,2.6 The application of array,【EG2-2】Scores sort Description: Given names and scores of 10 students, please find out the highest and lowest scores and names, output the average score of all 10 students. Analys

35、is: Store the students names and scores in a dictionary. Initialize the variable storing the highest score to 0, and the lowest score variable is initialized to 100. Each key in the dictionary is compared with the current highest score, the highest score variable is updated whenever a higher score i

36、s found; And also the key is compared with the current minimum score, the lowest score variable gets updated whenever a lower value is found. At the same time, the sum of scores is cumulated. Finally, the average score is calculated.,2.6 序列應(yīng)用,【例2-2】成績(jī)排序問(wèn)題 問(wèn)題描述:已知10個(gè)學(xué)生的姓名和成績(jī),請(qǐng)找出其中的最高分和最低分,并求出全班同學(xué)的平均分

37、。 分 析:將學(xué)生姓名和成績(jī)以健值對(duì)形式存放在一個(gè)字典中。初始化存放最高分的變量為0,存放最低分的變量為100。取出字典中每個(gè)鍵值對(duì),拿其值與目前的最高分比較,若大于最高分,則更新最高分;與目前的最低分比較,若小于最低分,則更新最低分。同時(shí)累加成績(jī)。最后,算出平均分。,2.6 序列應(yīng)用,2.6 序列應(yīng)用,程序: #score sort:Exp2_2.py studscore = 唐僧: 45, 孫悟空: 78, 豬八戒: 40, 沙僧: 96, 如來(lái): 65, 觀音: 90, 白骨精: 78, 紅孩兒: 99, 太上老君: 60, 白龍馬: 87 maxscore = 0 maxstudname = minscore = 100 minstudname = avrscore = 0 studnum = len(studscore) #輸出所有成績(jī): print

溫馨提示

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

最新文檔

評(píng)論

0/150

提交評(píng)論