Python程序设计-第2章-使用序列-2(第4次课).ppt

上传人:豆**** 文档编号:33188819 上传时间:2022-08-10 格式:PPT 页数:49 大小:367KB
返回 下载 相关 举报
Python程序设计-第2章-使用序列-2(第4次课).ppt_第1页
第1页 / 共49页
Python程序设计-第2章-使用序列-2(第4次课).ppt_第2页
第2页 / 共49页
点击查看更多>>
资源描述

《Python程序设计-第2章-使用序列-2(第4次课).ppt》由会员分享,可在线阅读,更多相关《Python程序设计-第2章-使用序列-2(第4次课).ppt(49页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、计算机编程导论 西南林业大学计算机与信息学院2014.3ReviewReviewChapter 2 Using Array Arrays Question 2-1、2-2、2-3 List Definition: , Create: = Read: ListNameindex Slices: ListNameindex1:index2 Adding: “+”, append(), extend(), insert() Search: count(), in, index() Delete: del, remove(), pop() Function: cmp( ),len( ),max( ),

2、min( ),sorted( ),reversed( ),sum( )复习复习第第2章章 表格处理表格处理 表格问题表格问题2-1、2-2 列表列表 定义定义 创建创建 读取读取 切片切片 添加添加 删除删除 函数函数2.4 Tuple A tuple is a compound data type. It is similar to a list except that it is immutable. Like list, a tuple is a comma-separated list of values. But tuples eIements in “( )”. For examp

3、le: (10, 20, 30, 40) (crunchy frog, ram bladder, lark vomit)2.4 元组元组 元组和列表类似,但其元素是不可变的,元组一旦创建,用任何方法都不可以修改其元素。 元组的定义方式和列表相同,但定义时所有元素是放在一对圆括号“(”和“)”中,而不是方括号中。 下面这些都是合法的元组: (10, 20, 30, 40) (crunchy frog, ram bladder, lark vomit)2.4 Tuple Operations(1)Create tuple Use the “=” to assign a tuple to a var

4、iable. a_tuple = (a, ) a_tuple(a,)a_tuple = (a, b, mpilgrim, z, example) a_tuple(a, b, mpilgrim, z, example)fNote: Without the comma,Python treats (a) as astring in parentheses2.4 元组元组(1)创建元组 使用“=”将一个元组赋值给变量。 例如: a_tuple = (a, ) a_tuple(a)a_tuple = (a, b, mpilgrim, z, example) a_tuple(a, b, mpilgrim

5、, z, example)注意:如不加逗号,(a)会被认为是放在括号中的字符串2.4 Tuple Operations(2)Read elements The operations on tuples are the same as lists. a_tuple2mpilgrim a_tuple-1example a_tuple-5a a_tuple-7Traceback (most recent call last): File , line 1, in a_tuple-7IndexError: tuple index out of range a_tuple5Traceback (most

6、 recent call last): File , line 1, in a_tuple5IndexError: tuple index out of range a_tuple=(a, b, mpilgrim, z, example)2.4 元组元组(2)读取元素)读取元素 用变量名加元素序号(放中括号中)即可访问元组中某个元素 同列表相同,元组的元素都有固定的顺序,第一个元素序号也为0,合法的元组元素序号的规定与列表相同。 例如: a_tuple2mpilgrim a_tuple-1example a_tuple-5a a_tuple-7Traceback (most recent ca

7、ll last): File , line 1, in a_tuple-7IndexError: tuple index out of range a_tuple5Traceback (most recent call last): File , line 1, in a_tuple5IndexError: tuple index out of range a_tuple=(a, b, mpilgrim, z, example)2.4 Tuple Operations(3)Slice The slice operator selects a range of elements from a t

8、uple: a_tuple1:3(b, mpilgrim)a_tuple=(a, b, mpilgrim, z, example)2.4 元组元组(3)元组切片)元组切片 与列表一样,元组也可以进行切片操作 对列表切片可以得到新的列表;对元组切片可以得到新的元组。 例如: a_tuple1:3(b, mpilgrim)a_tuple=(a, b, mpilgrim, z, example)2.4 Tuple Operations(4)Search Use count() method to calculate the number of elements in a tuple: a_tuple

9、.count(b)1 Use “in” to check whether an element is in a tuple: ab in a_tupleFalse z in a_tupleTrue Use the index( ) method to return the exact location of an element in the tuple: a_tuple.index(z)3 a_tuple.index(5)Traceback (most recent call last): File , line 1, in a_tuple.index(5)ValueError: tuple

10、.index(x): x not in tuplea_tuple=(a, b, mpilgrim, z, example)2.4 元组元组(4)检索元素)检索元素使用count( )方法计算元组中某个元素出现的次数;例如: a_tuple.count(b)1使用in运算符返回某个元素是否在该元组中;例如: ab in a_tupleFalse z in a_tupleTrue使用index( )方法返回某个元素在元组中的准确位置;例如: a_tuple.index(z)3 a_tuple.index(5)Traceback (most recent call last): File , lin

11、e 1, in a_tuple.index(5)ValueError: tuple.index(x): x not in tuplea_tuple=(a, b, mpilgrim, z, example)2.4 Tuple and ListDifferences and Conversion A tuple can not be 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 (

12、) or pop () method for tuples too. Tuples advantages: Faster Safer Can be used for dictionary keysTuples can be converted into lists, and vice-versa. tuple () function: list tuple list () function: tuple list f2.4 元组元组元组和列表的区别和转换元组和列表的区别和转换元组中的数据一旦定义就不允许更改。因此,元组没有append( )或extend( )方法,无法向元组中添加元素;元组没

13、有remove( )或pop( )方法,不能从元组中删除元素。元组与列表相比有下列优点优点:元组的速度比列表更快。如果定义了一系列常量值,而所需做的仅是对它进行遍历,那么一般使用元组而不用列表。元组对不需要改变的数据进行“写保护”将使得代码更加安全。一些元组可用作字典键(特别是包含字符串、数值和其它元组这样的不可变数据的元组)。列表永远不能当做字典键使用,因为列表不是不可变的。元组可转换转换成列表,反之亦然。内建的tuple( )函数接受一个列表参数,并返回一个包含同样元素的元组,而list( )函数接受一个元组参数并返回一个列表。从效果上看,tuple( )冻结列表,而list( )融化元组

14、。2.4 Tuple Operations Tuple assignment of multiple variables: v_tuple = (False, 3.5, exp) (x, y, z) = v_tuple xFalse y3.5 zexpa2.4 元组元组 可以利用元组来一次性的对多个变量赋值。例如: v_tuple = (False, 3.5, exp) (x, y, z) = v_tuple xFalse y3.5 zexp2.5 Dictionary1. DefinitionThe dictionary is an unordered set of key-value pa

15、irs.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)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_dic

16、t = server: db.diveintopython3.org, database: mysql a_dictdatabase: mysql, server: db.diveintopython3.orga2.5 字典字典1. 字典定义字典定义字典是键值对键值对的无序集合。字典中的每个元素包含两部分:键键和值值,向字典添加一个键的同时,必须为该键增添一个值。2. 字典的常用操作字典的常用操作(1)创建字典)创建字典定义字典时,每个元素的键和值用冒号分隔,元素之间用逗号分隔,所有的元素放在一对大括号“”和“”中。例如: a_dict = server: db.diveintopython3

17、.org, database: mysql a_dictdatabase: mysql, server: db.diveintopython3.org2.5 Dictionary Operations(2)SearchWe can use the keys of the dictionary to look up the valuesIn turn, may not a_dictserverdb.diveintopython3.org a_dictdatabasemysql a_dictdb.diveintopython3.orgTraceback (most recent call last

18、): File , line 1, in a_dictdb.diveintopython3.orgKeyError: db.diveintopython3.orgaa_dict=database: mysql, server: db.diveintopython3.org2.5 字典字典(2)查找值)查找值字典定义后,可以通过键来查找值,反之则不允许。例如: a_dictserverdb.diveintopython3.org a_dictdatabasemysql a_dictdb.diveintopython3.orgTraceback (most recent call last): F

19、ile , line 1, in a_dictdb.diveintopython3.orgKeyError: db.diveintopython3.orga_dict=database: mysql, server: db.diveintopython3.org2.5 Dictionary Operations(3)Traversal Use loop statement to traverse the keys and values of each element in the dictionaryfor key in a_dict.keys(): print(key, a_dictkey)

20、database mysqlserver db.diveintopython3.orgfa_dict=database: mysql, server: db.diveintopython3.org2.5 字典字典(3)遍历字典)遍历字典 可以用循环语句来遍历字典中每个元素的键和值。 例如:for key in a_dict.keys(): print key, a_dictkeydatabase mysqlserver db.diveintopython3.orga_dict=database: mysql, server: db.diveintopython3.org2.5 字典字典(3)遍

21、历字典)遍历字典 可以用循环语句来遍历字典中每个元素的键。 例如:for key in a_dict.keys(): print keyserverdatabase a_dict=database: mysql, server: db.diveintopython3.org2.5 字典字典(3)遍历字典)遍历字典 可以用循环语句来遍历字典中每个元素的值。 例如:for key in a_dict.keys(): print a_dictkeydb.diveintopython3.orgmysql for v in a_dict.values(): print vdb.diveintopytho

22、n3.orgmysqla_dict=database: mysql, server: db.diveintopython3.org2.5 Dictionary Operations(4)Adding and Modify Dictionaries have no size limit. We can 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_dictdat

23、abase: mysql, server: db.diveintopython3.org, user: mark a_dictdatabase=blog a_dictdatabase: blog, server: db.diveintopython3.org, user: markfa_dict=database: mysql, server: db.diveintopython3.org2.5 字典字典(4)添加和修改字典)添加和修改字典字典没有预定义的大小限制。可以随时向字典中添加新的键值对,或者修改现有键所关联的值添加和修改的方法相同,都是使用“字典变量名键名=键值”的形式,区分究竟是添

24、加还是修改是看键名与字典中现有的键名是否重复,因为字典中不允许有重复的键。如不重复则是添加新健值对,如重复则是将该键对应的值修改为新值。例如: a_dictuser = mark a_dictdatabase: mysql, server: db.diveintopython3.org, user: mark a_dictdatabase=blog a_dictdatabase: blog, server: db.diveintopython3.org, user: marka_dict=database: mysql, server: db.diveintopython3.org2.5 Di

25、ctionary Operations(5)Length Like lists and tuples, we can use the len () function to get the number of dictionaryelements. len(a_dict)3(6)Search We can use in to test whether a particular key is in the dictionary. server in a_dictTrue mysql in a_dictFalsefa_dict= database: blog, server: db.diveinto

26、python3.org, user: mark2.5 字典字典(5)字典长度)字典长度与列表、元组类似,可以用len( )函数返回字典中键的数量。例如: len(a_dict)3(6)字典检索)字典检索可以使用in运行符来测试某个特定的键是否在字典中。例如: server in a_dictTrue mysql in a_dictFalsea_dict= database: blog, server: db.diveintopython3.org, user: mark2.5 Dictionary Operations(7)Delete Del statement to remove a ke

27、y and its value, or the entire dictionary Clear () method to delete all the elements in the dictionary Pop () method to remove and return the specified key elements. del a_dictserver a_dictdatabase: blog, user: mark a_dict.pop(database)blog a_dictuser: mark a_dict.clear( ) a_dict del a_dict a_dictTr

28、aceback (most recent call last): File , line 1, in a_dictNameError: name a_dict is not defineda_dict= database: blog, server: db.diveintopython3.org, user: mark2.5 字典字典(7)删除元素和字典可以使用del语句删除指定键的元素或整个字典使用clear( )方法来删除字典中所有元素使用pop ()方法删除并返回指定键的元素。例如del a_dictserver将删除键值为server的元素a_dict.pop(database)将删除

29、并返回健为database的元素a_dict.clear()将删除字典中所有元素,del a_dict将删除整个字典。 del a_dictserver a_dictdatabase: blog, user: mark a_dict.pop(database)blog a_dictuser: mark a_dict.clear( ) a_dict del a_dict a_dictTraceback (most recent call last): File , line 1, in a_dictNameError: name a_dict is not defineda_dict= data

30、base: blog, server: db.diveintopython3.org, user: mark2.6 The application of array【EG2-1】Score statistics Description: 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: th

31、e scores are stored in a list. Four variables are defined and initialized to 0 to store the number of persons in each 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 序列应用序列应用【例【例2-1】 成绩统计问题 问题描述:问

32、题描述:已知10个成绩,请对其进行统计,输出优(10090)、良(8980)、中(7960)、差(590)四个等级的人数。 分分 析:析:将成绩存放在列表中。预设四个变量并初始化为0,用来存放四个等级的人数。对每个成绩进行判断,属哪个等级范围就将对应变量值加1。2.6 序列应用序列应用开始开始定义定义a、b、c、d四个变量并全部初始化为四个变量并全部初始化为0,它,它们分别对应优、良、中、差四个等级的人数们分别对应优、良、中、差四个等级的人数将将10个成绩存放在列表个成绩存放在列表score中中输出输出a、b、c、d四个统计结果四个统计结果结束结束对对score中每个成绩进行判断,是中每个成绩

33、进行判断,是哪个等级则对应变量自加哪个等级则对应变量自加1图2-3 成绩统计流程图2.6 序列应用序列应用程序:程序: #score count:Exp2_1.pyscore=68, 75, 32, 99, 78, 45, 88, 72, 83, 78a = 0b = 0c = 0d = 0#输出所有成绩print 成绩分别为:,for s in score: print s,#换行print#对成绩进行分段统计对成绩进行分段统计for s in score: if s 60: d = d + 1 elif s 80: c = c + 1 elif s maxscore: maxscore =

34、 studscorekey maxstudname = key if studscorekey minscore: minscore = studscorekey minstudname = key avrscore = avrscore + studscorekeyavrscore = avrscore / studnumprint 全班共有全班共有,studnum,人人,平均成绩为:平均成绩为:,avrscore,分。分。print 最高分是:最高分是:,maxstudname,maxscore,分分print 最低分是:最低分是:,minstudname,minscore,分分2.6 序

35、列应用序列应用程序运行结果:程序运行结果:成绩分别为:红孩儿 99 ; 白龙马 87 ; 观音 90 ; 唐僧 45 ; 白骨精 78 ; 猪八戒 40 ; 太上老君 60 ; 如来 65 ; 孙悟空 78 ; 沙僧 96 ;全班共有 10 人,平均成绩为: 73 分。最高分是: 红孩儿 99 分最低分是: 猪八戒 40 分2.6 序列应用序列应用【例【例2-3】用字典完成例2-1分析:定义一个字典 a=差:0,中:0,良:0,优:0 用值来统计人数。程序:程序:score=68, 75, 32, 99, 78, 45, 88, 72, 83, 78a=差差:0,中中:0,良良:0,优优:0f

36、or s in score: if s60: a差差=a差差+1 elif s80: a中中=a中中+1 elif s90: a良良=a良良+1 else: a优优=a优优+1for key in a: print key,akey,人人Summary List Definition Operate: Create, Read, Slices, Adding, Search, Delete Tuple Definition Operate: Create, Read, Slices, Search Dictionaries Definition Operate: Create, Search, Traversal, Adding, Modify, Length, Delete本章小结本章小结 列表 定义 操作:创建、读取、切片、添加、查找、删除 元组 定义 操作:创建、读取、切片、查找 字典 定义 操作:创建、查找、遍历、添加、更新、求长度、删除第第4次上机作业次上机作业习题2.3习题2.4习题2.5仅上机作业仅上机作业4.将本章课件中涉及的所有源程序在Python下输入、调试并运行5.将本章课件中所有的交互式命令在Python的IDLE中调试

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁