Python入门教程

上传人:gbs****77 文档编号:9818364 上传时间:2020-04-08 格式:DOCX 页数:90 大小:456.05KB
返回 下载 相关 举报
Python入门教程_第1页
第1页 / 共90页
Python入门教程_第2页
第2页 / 共90页
Python入门教程_第3页
第3页 / 共90页
点击查看更多>>
资源描述
火 龙 果 整 理uml orgcn Python 入门教程 1 Python Syntax 1 Python 是一个高效的语言 读和写的操作都是很简单的 就像普通的英语一样 2 Python 是一个解释执行的语言 我们不需要去编译 我们只要写出代码即可运行 3 Python 是一个面向对象的语言 在 Python 里面一切皆对象 4 Python 是一门很有趣的语言 5 变量 一个变量就是一个单词 只有一个单一的值 练习 设置一个变量 my variable 值设置为 10 cpp Write your code below my variable 10 3 第三节 1 Python 里面有三种数据类型 interage floats booleans 2 Python 是一个区分大小写的语言 3 练习 1 把变量 my int 值设置为 7 2 把变量 my float 值设置为 1 23 3 把变量 my bool 值设置为 true python 火 龙 果 整 理uml orgcn Set the variables to the values listed in the instructions my int 7 my float 1 23 my bool True 6 Python 的变量可以随时进行覆盖 2 练习 my int 的值从 7 改为 3 并打印出 my int python my int is set to 7 below What do you think will happen if we reset it to 3 and print the result my int 7 Change the value of my int to 3 on line 8 my int 3 Here s some code that will print my int to the console The print keyword will be covered in detail soon print my int 火 龙 果 整 理uml orgcn 7 Pyhton 的声明和英语很像 8 Python 里面声明利用空格在分开 3 练习 查看以下代码的错误 python def spam eggs 12 return eggs print spam 9 Python 中的空格是指正确的缩进 2 练习 改正上一节中的错误 python def spam eggs 12 return eggs print spam 10 Python 是一种解释执行的语言 只要你写完即可立即运行 2 练习 设置变量 spam 的只为 True eggs 的值为 False python 火 龙 果 整 理uml orgcn spam True eggs False 11 Python 的注释是通过 来实现的 并不影响代码的实现 2 练习 给下面的代码加上一行注释 python this is a comments for Python mysterious variable 42 12 Python 的多行注释是通过 来实现的 2 练习 把下面的代码加上多行 python this is a Python course a 5 13 Python 有 6 种算术运算符 幂 2 练习 把变量 count to 设置为 1 2 python Set count to equal to 1 plus 2 on line 3 火 龙 果 整 理uml orgcn count to 1 2 print count to 14 Python 里面求 x m 写成 x m 2 练习 利用幂运算 把 eggs 的值设置为 100 python Set eggs equal to 100 using exponentiation on line 3 eggs 10 2 print eggs 1 练习 1 写一行注释 2 把变量 monty 设置为 True 3 把变量 python 值设置为 1 234 4 把 monty python 的值设置为 python 的平方 python this is a Python monty True python 1 234 monty python python 2 火 龙 果 整 理uml orgcn Python 入门教程 2 Tip Calculator 1 把变量 meal 的值设置为 44 50 python Assign the variable meal the value 44 50 on line 3 meal 44 50 1 把变量 tax 的值设置为 6 75 python meal 44 50 tax 6 75 100 1 设置 tip 的值为 15 python You re almost there Assign the tip variable on line 5 meal 44 50 火 龙 果 整 理uml orgcn tax 0 0675 tip 0 15 1 把变量 meal 的值设置为 meal meal tax python Reassign meal on line 7 meal 44 50 tax 0 0675 tip 0 15 meal meal meal tax 设置变量 total 的值为 meal meal tax python Assign the variable total on line 8 meal 44 50 tax 0 0675 tip 0 15 meal meal meal tax total meal meal tip print 2f total 火 龙 果 整 理uml orgcn Python 入门教程 3 Strings and Console Output 15 Python 里面还有一种好的数据类型是 String 16 一个 String 是通过 或者 包成的串 3 设置变量 brian 值为 Always look on the bright side of life python Set the variable brian on line 3 brian Always look on the bright side of life 1 练习 1 把变量 caesar 变量设置为 Graham 2 把变量 praline 变量设置为 john 3 把变量 viking 变量设置为 Teresa python Assign your variables below each on its own line caesar Graham praline John viking Teresa Put your variables above this line print caesar print praline 火 龙 果 整 理uml orgcn print viking 17 Python 是通过 来实现转义字符的 2 练习把 Help Help I m being repressed 中的 I m 中的 进行转义 python The string below is broken Fix it using the escape backslash Help Help m being repressed 18 我们可以使用 来避免转义字符的出现 2 练习 把变量 fifth letter 设置为 MONTY 的第五个字符 python The string PYTHON has six characters numbered 0 to 5 as shown below P Y T H O N 0 1 2 3 4 5 So if you wanted Y you could just type PYTHON 1 always start counting from 0 火 龙 果 整 理uml orgcn fifth letter MONTY 4 print fifth letter 19 介绍 String 的第一种方法 len 求字符串的长度 2 练习 把变量 parrot 的值设置为 Norweigian Blue 然后打印 parrot 的长度 python parrot Norwegian Blue print len parrot 20 介绍 String 的第二种方法 lower 把所有的大写字母转化为小写字母 2 练习 把 parrot 中的大写字母转换为小写字母并打印 python parrot Norwegian Blue print parrot lower 21 介绍 String 的第三种方法 upper 把所有的大写字母转化为小写字母 2 练习 把 parrot 中的小写字母转换为大写字母并打印 火 龙 果 整 理uml orgcn python parrot norwegian blue print parrot upper 第八节 1 介绍 String 的第四种方法 str 把非字符串转化为字符串 比如 str 2 是把 2 转化 为字符串 2 2 练习 设置一个变量 pi 值为 3 14 把 pi 转化为字符串 python Declare and assign your variable on line 4 then call your method on line 5 pi 3 14 print str pi 22 主要介绍 的用处 比如上面的四个 String 的四个方法都是用到了点 2 练习 利用 来使用 String 的变量 ministry 的函数 len 和 upper 并打印 出 python ministry The Ministry of Silly Walks print len ministry 火 龙 果 整 理uml orgcn print ministry upper 23 介绍 print 的作用 2 练习 利用 print 输出字符串 Monty Python python Tell Python to print Monty Python to the console on line 4 print Monty Python 1 介绍 print 来打印出一个变量 2 练习 把变量 the machine goes 值赋值 Ping 然后打印出 python Assign the string Ping to the variable the machine goes on line 5 then print it out on line 6 the machine goes Ping print the machine goes 24 介绍我们可以使用 来连接两个 String 2 练习 利用 把三个字符串 Spam 和 and 和 eggs 连接起来输出 火 龙 果 整 理uml orgcn python Print the concatenation of Spam and eggs on line 3 print Spam and eggs 25 介绍了 str 的作用是把一个数字转化为字符串 2 练习 利用 str 函数把 3 14 转化为字符串并输出 python Turn 3 14 into a string on line 3 print The value of pi is around str 3 14 第十四节 1 介绍了字符串的格式化 使用 来格式化 字符串是 s 2 举例 有两个字符串 利用格式化 s 来输出 python string 1 Camelot string 2 place print Let s not go to s Tis a silly s string 1 string 2 火 龙 果 整 理uml orgcn 1 回顾之前的内容 2 练习 1 设置变量 my string 的值 2 打印出变量的长度 3 利用 upper 函数并且打印变量值 python Write your code below starting on line 3 my string chenguolin print len my string print my string upper Python 入门教程 4 Date and Time 26 介绍得到当前的时间 datetime now 2 练习 1 设置变量 now 的值为 datetime now 2 打印 now 的值 python from datetime import datetime now datetime now print now 火 龙 果 整 理uml orgcn 27 介绍从 datetime now 得到的信息中提取出 year month 等 2 练习 从 datetime now 中得到的信息中提取出 year month day python from datetime import datetime now datetime now print now month print now day print now year 28 介绍把输出日期的格式转化为 mm dd yyyy 我们利用的是 来转化 2 练习 打印当前的日期的格式为 mm dd yyyy python from datetime import datetime now datetime now print str now month str now day str now year 29 介绍把输出的时间格式化为 hh mm ss 2 练习 打印当前的时间的格式为 hh mm ss 火 龙 果 整 理uml orgcn python from datetime import datetime now datetime now print str now hour str now minute str now second 第五节 1 练习 把日期和时间两个连接起来输出 python from datetime import datetime now datetime now print str now month str now day str now year str now hour str now minute str now second Python 入门教程 5 Conditionals One animal is missing if len zoo animals 3 print The first animal at the zoo is the zoo animals 0 print The second animal at the zoo is the zoo animals 1 print The third animal at the zoo is the zoo animals 2 print The fourth animal at the zoo is the zoo animals 3 58 介绍了我们可以使用下标来访问 list 的元素 就像数组一样 2 下标从 0 开始 比如 list name 0 是第一个元素 3 练习 输出列表 numbers 的第二个和第四个数的和 python numbers 5 6 7 8 print Adding the numbers at indices 0 and 2 print numbers 0 numbers 2 火 龙 果 整 理uml orgcn print Adding the numbers at indices 1 and 3 Your code here print numbers 1 numbers 3 59 介绍了我们可以使用下标来对第几个元素进行赋值 2 比如 lisy name 2 2 就是把列表的第三个值赋值为 2 3 练习 把列表 zoo animals 中的 tiger 换成其它的动物 python zoo animals pangolin cassowary sloth tiger Last night our zoo s sloth brutally attacked the poor tiger and ate it whole The ferocious sloth has been replaced by a friendly hyena zoo animals 2 hyena What shall fill the void left by our dear departed tiger Your code here zoo animals 3 dog 60 介绍了 list 中添加一个 item 的方法 append 2 比 list name append item 求列表 list name 中有几项就是利用 len list name 3 练习 在列表 suitcase 在增加三项 然后求出它的元素的个数 火 龙 果 整 理uml orgcn python suitcase suitcase append sunglasses Your code here suitcase append a suitcase append b suitcase append c Set this to the length of suitcase list length len suitcase print There are d items in the suitcase list length print suitcase 61 介绍了 list 列表怎样得到子列表 list name a b 将得到下标 a 开始到下标 b 之前的 位置 2 比如列表 my list 1 2 3 4 那么 my list 1 3 得到的将是 2 3 python my list 0 1 2 3 my slice my list 1 3 print my list 火 龙 果 整 理uml orgcn Prints 0 1 2 3 print my slice Prints 1 2 3 如果我们默认第二个值 那么将会直接到末尾那个位置 如果默认第一个值 值是 从头开始 python my list 2 Grabs the first two items my list 3 Grabs the fourth through last 4 练习 把 first 列表设置为 suitcase 的前两项 把 middle 列表设置为 suitcase 的中间两项 把 last 列表设置为 suitcase 的后两项 python suitcase sunglasses hat passport laptop suit shoes The first two items first suitcase 0 2 Third and fourth items middle suitcase 2 4 The last two items last suitcase 4 火 龙 果 整 理uml orgcn 62 介绍了不仅列表可以得到子串 字符串也满足 2 比如 string a b 是得到从下标 a 开始到 b 之前的子串 3 练习 把三个变量分别设置为对应的子串 python animals catdogfrog The first three characters of animals cat animals 3 The fourth through sixth characters dog animals 3 6 From the seventh character to the end frog animals 6 63 介绍了列表的两种方法 index item 和 insert index item 2 index item 方法是查找 item 在列表中的下标 使用方法 list name index item 3 insert index item 是在下标 index 处插入一个 item 其余的后移 使用方法 list name insert index item 4 练习 使用 index 函数找到列表中的 duck 然后在当前位置插入 cobra 如果我们使用 print list name 就是直接输出列表的所有元素 python animals aardvark badger duck emu fennec fox Use index to find duck duck index animals index duck 火 龙 果 整 理uml orgcn Your code here animals insert duck index cobra Observe what prints after the insert operation print animals 64 介绍我们可以使用 for 循环来遍历列表的每一个元素 2 比如 for variable in list name statement 这样我们可以枚举列表的每一个元素 3 练习 打印列表的每一个元素的值 2 python my list 1 9 3 8 5 7 for number in my list Your code here print 2 number 65 介绍了列表的另外一种方法 sort 可以对列表进行排序 默认是从小到打排序 2 使用的方法是 list name sort 3 列表中删除一个 item 的方法 list name remove item 火 龙 果 整 理uml orgcn python beatles john paul george ringo stuart beatles remove stuart print beatles john paul george ringo 4 练习 利用 for 循环把没一项的值的平方加入列表 square list 然后对 square list 排序输出 python start list 5 3 1 2 4 square list Your code here for numbers in start list square list append numbers 2 print square list sort 66 介绍了 Python 中的字典 字典的每一个 item 是一个键值对即 key value 注意 字典是无序的 所以 for I in dec 中 i 指的是 Key 值 而 dec i 则是 value 值 2 比如字典 d key1 1 key2 2 key3 3 有三个元素 3 Python 的字典和 C 里面的 map 很像 我们可以使用 d key1 来输出 key1 对应 的 value 4 练习 打印出 Sloth 和 Burmese Python 对应的 value 注意在脚本语言里面可以使用单引号也可以使用双引号来表示字符串 火 龙 果 整 理uml orgcn python Assigning a dictionary with three key value pairs to residents residents Puffin 104 Sloth 105 Burmese Python 106 Prints Puffin s room number print residents Puffin Your code here print residents Sloth print residents Burmese Python 67 字典和列表一样可以是空的 比如 d 就是一个空的字典 68 字典里面添加一个键值对或者是改变已有 key 的 value 使用这种方法 dict name key value 69 我们也可以使用 len dict name 求出字典的元素的个数 2 练习 至少添加 3 个键值对到字典 menu 中 python Empty dictionary menu Adding new key value pair 火 龙 果 整 理uml orgcn menu Chicken Alfredo 14 50 print menu Chicken Alfredo Your code here Add some dish price pairs to menu menu a 1 menu b 2 menu c 3 print you code print There are str len menu items on the menu print menu 70 介绍了我们可以删除字典中的键值对 2 我们使用 del dict name key 这样将删除键值为 key 的键值对 3 练习 删除 key 为 Sloth 和 Bengal Tiger 并且设置 key 为 Rockhopper Penguin 的 val 和之前的不一样 python key animal name value location zoo animals Unicorn Cotton Candy House Sloth Rainforest Exhibit Bengal Tiger Jungle House Atlantic Puffin Arctic Exhibit 火 龙 果 整 理uml orgcn Rockhopper Penguin Arctic Exhibit A dictionary or list declaration may break across multiple lines Removing the Unicorn entry Unicorns are incredibly expensive del zoo animals Unicorn Your code here del zoo animals Sloth del zoo animals Bengal Tiger zoo animals Rockhopper Penguin aa print you code print zoo animals 71 介绍了字典中一个 key 可以对应不止一个的 value 2 比如 my dict hello h e l l o 那么 key 为 hello 对应的 value 有 5 个 我们可以使用 my dict hello index 来取得下标为 index 的 value 比 如 index 为 1 的时候是 e 3 对于一个 key 对应多个 value 的话 我们应该要用 list 来保存这些 value 4 对于一个 key 对应多个 value 的话 我们还可以对这个 key 的 val 进行排序 比如 my dict hello sort 4 练习 火 龙 果 整 理uml orgcn 1 在字典 inventory 中添加一个 key 为 pocket 值设置为列表 seashell strange berry lint 2 对 key 为 pocket 的 value 进行排序 3 删除字典 inventory 中 key 为 backpack 的键值对 4 把字典 inventory 中 key 为 gold 的 value 加一个 50 python Assigned a new list to pouch key inventory gold 500 pouch flint twine gemstone backpack xylophone dagger bedroll bread loaf Adding a key burlap bag and assigning a list to it inventory burlap bag apple small ruby three toed sloth Sorting the list found under the key pouch inventory pouch sort Here the dictionary access expression takes the place of a list name Your code here inventory pocket seashell strange berry lint inventory pocket sort del inventory backpack inventory gold 500 50 火 龙 果 整 理uml orgcn 外记 1 sort 函数的深度使用 Python 语言内置了 sort 方法 可以很方便地对某个 List 进行排序 L 6 5 1 3 4 2 L sort print L Run Python Program 1 2 3 4 5 6 某些时候 我们希望按照自己定义的排序规则来排序 例如 按关键词的权重排序 按人的年 龄排序 等等 在 Java 语言中 我们可以自定义 Comparator 来实现 Python 中也提供 了类似的办法 若 List 中每个元素都是 2 tuple tuple 中第一个元素为 String 类型的 keyword 第二个元 素为该字符串对应的权重 int 类型 希望按照权重排序 从高到低 则可以这样 def my cmp E1 E2 return cmp E1 1 E2 1 compare weight of each 2 tuple return the negative result of built in cmp function thus we get the descend order L a 0 b 1 c 2 d 3 L sort my cmp print L Run Python Program d 3 c 2 b 1 a 0 火 龙 果 整 理uml orgcn 正因为可以自定义 cmp 方法 我们不妨探究一下 built in 的 sort 方法 到底是采用的哪一 种排序算法 from random import shuffle def my cmp E1 E2 print E1 E1 E2 E2 return cmp E1 E2 L range 0 10 shuffle L print L L sort my cmp Run Python Program 5 3 7 6 2 8 9 4 1 0 E1 3 E2 5 E1 7 E2 3 E1 7 E2 5 E1 6 E2 5 E1 6 E2 7 E1 2 E2 6 E1 2 E2 5 E1 2 E2 3 E1 8 E2 5 E1 8 E2 7 E1 9 E2 6 E1 9 E2 8 E1 4 E2 6 E1 4 E2 3 E1 4 E2 5 E1 1 E2 6 E1 1 E2 4 E1 1 E2 3 E1 1 E2 2 E1 0 E2 5 E1 0 E2 3 E1 0 E2 2 E1 0 E2 1 火 龙 果 整 理uml orgcn 可以看到 每次调用 my cmp E1 依次是 List 中的第 2 3 4 直到最后一个元素 可以 肯定 sort 不是采用的分治法 devide and conqure 看前三次调用 可以发现 sort 采用的是典型的插入排序 也就是说 将新元素插入已排序部 分的合适位置 查找位置时采用的似乎是从后向前线形探察的办法 从元素 6 开始 新元素不 再直接与已排序部分的最后元素比较 而是先与中间值比较 采用二分检索探察合适位置 这 样 可以把时间代价从 n 缩小到 log n 至此 我们可以认为 built in 的 sort 方法 采用的是 二分法插入排序 binary insertion 的算法 为了检测这个结论 可以输入一个已排序的数组 看看结果 L 0 1 2 3 4 5 6 7 8 9 10 L sort my cmp Run Python Program E1 1 E2 0 E1 2 E2 1 E1 3 E2 2 E1 4 E2 3 E1 5 E2 4 E1 6 E2 5 E1 7 E2 6 E1 8 E2 7 E1 9 E2 8 E1 10 E2 9 结果发现 比较的次数非常少 插入每个元素的时候 只会与它之前紧邻的元素比较 而不是 二分检索 这真是个有意思的现象 改一改程序 L 0 1 2 3 4 5 6 8 7 9 10 L sort my cmp Run Python Program E1 1 E2 0 E1 2 E2 1 E1 3 E2 2 E1 4 E2 3 E1 5 E2 4 E1 6 E2 5 火 龙 果 整 理uml orgcn E1 8 E2 6 E1 7 E2 8 E1 7 E2 4 E1 7 E2 6 E1 7 E2 8 E1 9 E2 4 E1 9 E2 7 E1 9 E2 8 E1 10 E2 5 E1 10 E2 8 E1 10 E2 9 可以看到 在数字 8 以前 List 中的元素都是有序的 于是 sort 算法也只比较欲插入元素和 已排序序列的最后一个元素 一旦发现输入序列不是自然有序之后 就采用二分插入排序算法 这样的混合排序算法 相对单纯的插入排序 保证了最好条件下时间代价最低 也减小了一般 情况下的时间代价 p s 写完之后查阅 Python 的文档 发现 sort 采用的是混合 hybrid 排序 规模小的时候采用 binary insertion 规模大的时候采用 samplesort 据说是 quicksort 的一个变种 我没接 触过 汗 外记 2 Python 的 url 编码函数使用的一个小问题 python 的 url 编码函数是在类 urllib 库中 使用方法是 编码 urllib quote string safe 除了三个符号 外 将所有符号编码 后面的参数 safe 是不编码的字符 使用的时候如果不设置的话 会将斜杠 冒号 等号 问号都给编码了 print urllib quote print urllib quote 结果如下 火 龙 果 整 理uml orgcn http 3A 外记 3 python 对文件进行读写操作 python 进行文件读写的函数是 open 或 file file handler open filename mode Table mode 模 式 描述 r 以读方式打开文件 可读取文件信息 w 以写方式打开文件 可向文件写入信息 如文件存在 则清空该文件 再写入新内容 a 以追加模式打开文件 即一打开文件 文件指针自动移到文件末尾 如果文件不存在则创建 r 以读写方式打开文件 可对文件进行读和写操作 w 消除文件内容 然后以读写方式打开文件 a 以读写方式打开文件 并把文件指针移到文件尾 b 以二进制模式打开文件 而不是以文本模式 该模式只对 Windows 或 Dos 有效 类Unix 的文件是用二进制模式进行操作的 火 龙 果 整 理uml orgcn Table 文件对象方法 方法 描述 f close 关闭文件 记住用 open 打开文件后一定要记得关闭它 否则会占用系统的可打开文件句柄数 f fileno 获得文件描述符 是一个数字 f flush 刷新输出缓存 f isatty 如果文件是一个交互终端 则返回 True 否则返回 False f read count 读出文件 如果有 count 则读出 count 个字节 f readline 读出一行信息 f readlines 读出所有行 也就是读出整个文件的信息 f seek offset where 把文件指针移动到相对于 where 的 offset 位置 where 为 0 表示文件开始处 这是默认值 1 表 示当前位置 2 表示文件结尾 f tell 获得文件指针位置 f truncate size 截取文件 使文件的大小为 size f write string 把 string 字符串写入文件 f writelines list 把 list 中的字符串一行一行地写入文件 是连续 写入文件 没有换行 例子如下 读文件 Python 代码 1 read open result 2 line read readline 火 龙 果 整 理uml orgcn 3 while line 4 print line 5 line read readline 如果没有这行会造成死循环 6 read close 写文件 Python 代码 1 read file result a 2 read write r n 3 read write thank you 4 read close 其它 Python 代码 1 encoding UTF 8 2 filehandler open c 111 txt r 以读方式打开文件 rb 为二进制方式 如图 片或可执行文件等 3 4 print read function 读取整个文件 5 print filehandler read 6 7 print readline function 返回文件头 读取一行 8 filehandler seek 0 9 print filehandler readline 10 11 print readlines function 返回文件头 返回所有行的列表 12 filehandler seek 0 13 print filehandler readlines 火 龙 果 整 理uml orgcn 14 15 print list all lines 返回文件头 显示所有行 16 filehandler seek 0 17 textlist filehandler readlines 18 for line in textlist 19 print line 20 print 21 print 22 23 print seek 15 function 移位到第 15 个字符 从 16 个字符开始显示 余下内容 24 filehandler seek 15 25 print tell function 26 print filehandler tell 显示当前位置 27 print filehandler read 28 29 filehandler close 关闭文件句柄 6 外记 4 python 数组的使用 python 数组的使用 2010 07 28 17 17 1 Python 的数组分三种类型 1 list 普通的链表 初始化后可以通过特定方法动态增加元素 火 龙 果 整 理uml orgcn 定义方式 arr 元素 2 Tuple 固定的数组 一旦定义后 其元素个数是不能再改变的 定义方式 arr 元素 2 Dictionary 词典类型 即是 Hash 数组 定义方式 arr 元素 k v 2 下面具体说明这些数组的使用方法和技巧 1 list 链表数组 a 定义时初始化 a 1 2 1 2 3 b 定义时不初始化 一维数组 arr 多维数组 arr i for i in range 10 1 注意 i for in xx 这个必须放在第一个位置 否则要 先定义 i 如 arr i for i in range 5 j for j in range 5 这是错误的 i 0 j 0 arr i for i in range 5 j for j in range 5 这是正确的 c del 语句 和 的用法 可以用 start end 表示数组里的一个区间 i start and i t a b c d e 1 用小括号包围来定义 t a b c d e t 0 2 直接列出某下标的元素 a t 1 3 负数表示 从后面倒数的索引 1 为倒数第一 个 0 是顺数第一个 example t 1 3 4 这里 1 3 是 i 1 and i 3 的区间 b mpilgrim Tuple 没有的方法 1 不能向 tuple 增加元素 没有 append extend insert 等方法 2 不能从 tuple 删除元素 没有 remove 或 pop 方法 3 不能在 tuple 中查找元素 没有 index 方法 index 是查找而不是索引 索引直接用下 标即可 如 t 0 使用 tuple 的好处 Tuple 比 list 操作速度快 如果您定义了一个值的常量集 并且唯一要用它做的是不断地 遍历它 请使用 tuple 代替 list 如果对不需要修改的数据进行 写保护 可以使代码更安全 使用 tuple 而不是 list 如同 拥有一个隐含的 assert 语句 说明这一数据是常量 如果必须要改变这些值 则需要执行 tuple 到 list 的转换 需要使用一个特殊的函数 还记得我说过 dictionary keys 可以是字符串 整数和 其它几种类型 吗 Tuples 就是 这些类型之一 Tuples 可以在 dictionary 中被用做 key 但是 list 不行 实际上 事情 要比这更复杂 Dictionary key 必须是不可变的 Tuple 本身是不可改变的 但是如果您有 一个 list 的 tuple 那就认为是可变的了 用做 dictionary key 就是不安全的 只有字符 串 整数或其它对 dictionary 安全的 tuple 才可以用作 dictionary key Tuple 可以转换成 list 反之亦然 转换方式为 t list t 反之 arr tuple arr 火 龙 果 整 理uml orgcn 2 Dictionary 哈希数组 词典数组 Dictionary 的用法比较简单 它可以存储任意值 并允许是不同类型的值 下面实例来说明 下面例子中 a 是整数 b 是字符串 c 是数组 这个例子充分说明哈希数组的适用性 dict arr a 100 b boy c o p q 可以直接增加一个元素 如果同名 则会改变原来的 key 的元素的值 dict arr d dog 输出所有的 key print dict arr keys 输出所有的 value print dict arr values 遍历数组 import types for k in dict arr v dict arr get k if type v is types ListType 如果数据是 list 类型 继续遍历 print k for kk vv in enumerate v print kk vv print else print dict arr get k list 的方法 L append var 追加元素 L insert index var L pop var 返回最后一个元素 并从 list 中删除之 L remove var 删除第一次出现的该元素 L count var 该元素在列表中出现的个数 L index var 该元素的位置 无则抛异常 L extend list 追加 list 即合并 list 到 L 上 L sort 排序 L reverse 倒序 list 操作符 关键字 del a 1 片段操作符 用于子 list 的提取 1 2 3 4 为 1 2 3 4 同 extend 2 4 为 2 2 2 2 del L 1 删除指定下标的元素 del L 1 3 删除指定下标范围的元素 火 龙 果 整 理uml orgcn list 的复制 L1 L L1 为 L 的别名 用 C 来说就是指针地址相同 对 L1 操作即对 L 操作 函数参数就 是这样传递的 L1 L L1 为 L 的克隆 即另一个拷贝 list comprehension for k in L if 2 dictionary 字典 即 C 标准库的 map dict ob1 computer ob2 mouse ob3 printer 每一个元素是 pair 包含 key value 两部分 key 是 Integer 或 string 类型 value 是任 意类型 键是唯一的 字典只认最后一个赋的键值 dictionary 的方法 D get key 0 同 dict key 多了个没有则返回缺省值 0 没有则抛异常 D has key key 有该键返回 TRUE 否则 FALSE D keys 返回字典键的列表 D values D items D update dict2 增加合并字典 D popitem 得到一个 pair 并从字典中删除它 已空则抛异常 D clear 清空字典 同 del dict D copy 拷贝字典 D cmp dict1 dict2 比较字典 优先级为元素个数 键大小 键值大小 第一个大返回 1 小返回 1 一样返回 0 dictionary 的复制 dict1 dict 别名 dict2 dict copy 克隆 即另一个拷贝 3 tuple 元组 即常量数组 tuple a b c d e 可以用 list 的 操作符提取元素 就是不能直接修改元素 4 string 字符串 即不能修改的字符 list str Hello My friend 字符串是一个整 体 如果你想直接修改字符串的某一部分 是不可能的 但我们能够读出字符 串的某一部分 子字符串的提取 str 6 字符串包含 判断操作符 in not in He in str 火 龙 果 整 理uml orgcn she not in str string 模块 还提供了很多方法 如 S find substring start end 可指范围查找子串 返回索引值 否则返回 1 S rfind substring start end 反向查找 S index substring start end 同 find 只是找不到产生 ValueError 异常 S rindex substring start end 同上反向查找 S count substring start end 返回找到子串的个数 S lowercase S capitalize 首字母大写 S lower 转小写 S upper 转大写 S swapcase 大小写互换 S split str 将 string 转 list 以空格切分 S join list 将 list 转 string 以空格连接 处理字符串的内置函数 len str 串长度 cmp my friend str 字符串比较 第一个大 返回 1 max abcxyz 寻找字符串中最大的字符 min abcxyz 寻找字符串中最小的字符 string 的转换 oat str 变成浮点数 float 1e 1 结果为 0 1 int str 变成整型 int 12 结果为 12 int str base 变成 base 进制整型数 int 11 2 结果为 2 long str 变成长整型 long str base 变成 base 进制长整型 字符串的格式化 注意其转义字符 大多如 C 语言的 略 str format 参数列表 6 列表切片操作 1 a 1 2 3 4 5 2 a 2 iterate over the whole list in 2 increments 3 1 3 5 4 5 列表逆序 火 龙 果 整 理uml orgcn 6 a 1 7 5 4 3 2 1 8 利用字典格式化字符串 view p
展开阅读全文
相关资源
相关搜索

当前位置:首页 > 办公文档 > 解决方案


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


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