======================= Lecture Notes on Python ======================= :Authors: 蓝珲 (lanhui AT zjnu.edu.cn) :Version: 0.1.5 of 2019-07-26 .. contents:: 内容目录 前言 -------------------------------------------------------------------- .. 非学究写书,无空洞行文。 Python语法简洁,库函数全面强大,编程速度快,运行速度也不慢。 大学里, 往往是专家教初学者。 专家也是从初学者过来的,只不过专家经常忘 记这一点。 要知道,初学者可能只写过不到10行的程序,而专家已经写了至少 10000行程序了。 两者的大脑构造不同。 学习是困难的, 教育或培训应把专 家的工作流程放慢100倍! 初学者要做的是尽量快的使自己的程序量到达1000, 这包括中间无数次除错, 每次除错都是一次微小的学习。 要想感到舒服, 只 有积累自己的经验, 无其它捷径。 面对新东西,初学者往往会问这些困惑 (蔡彬彬 or 伍丽丽?): - 这个东西是什么意思? - 怎么来的? - 有什么用? - 怎么用? - 什么情况下用? - 为什么程序中要加入这个东西? 动态的教育方式会更好。专家与初学者坐在电脑前, 逐步回答上述问题, 直到 初学者说“我明白了”。 Python的发音纠正 ------------------------------ 国人普遍把th发作s。 Not quite correct。 \ ˈpī-ˌthän , -thən\ pronounciation_ .. _pronounciation: https://cn.bing.com/search?q=define%20python&tf=U2VydmljZT1EaWN0aW9uYXJ5QW5zd2VyVjIgU2NlbmFyaW89RGVmaW5pdGlvblNjZW5hcmlvIFBvc2l0aW9uPU5PUCBSYW5raW5nRGF0YT1UcnVlIEZvcmNlUGxhY2U9RmFsc2UgUGFpcnM9RGljdGlvbmFyeVdvcmQ6cHl0aG9uO3NjbjpEZWZpbml0aW9uU2NlbmFyaW87cDpRQVM7IHw%3d&hs=hyRBF0mYq9hrfQUq66DIZnFVta1ZGRfBiBks25oUguk%3d Python源流 ------------------------------ Python之父Guido van Rossum,荷兰人,1956年生,1982年阿姆斯特丹大学获得 数学与计算机科学硕士学位。有过ABC语言的工作经验。1989年设计了Python语 言。 Python语法简洁,有大而全而有用的标准库。 自然(natural)语言。特点:歧义,重复。“The penny dropped。” “不要。” 正式(formal)语言。特点:只管字面意思。 计算机组成概要:CPU,总线,内存,硬盘。 Bit, byte, KB, MB, GB, TB换算。 变量的命名。如,层叠策略,用CDCL还是TiledStrategy? 教务管理系统,http://10.1.70.164/jwglxt? 习语言、易语言等目前非主流语言。 Python能做什么? ----------------------------------------------------- 可以当一个计算器。 交互模式。 可以处理大量文本。 强大的标准库。 可以画图。 库matlibplot。 可以写简单的游戏。库pygame。 可以做科学计算。 numpy, scipy。 可以做机器学习,比如人脸识别。 可以做网路爬虫。 可以做网页应用程序。 Flask。 只要有对应的库,几乎什么都可以做。 如果没有库, 可以自己写库。 当然, 要想写一个有用的、受欢迎的库不是简简单单一蹴而就的事情。 很多情况下需要有公司的支援。 把现实的问题转化为计算机可以处理的问题 ----------------------------------------------------- 为什么需要程序呢? 因为运算快, 处理数据快, 且没有情绪。 如果我问你, 下面的文字中有几个apple? 你一定可以很快的告诉我。 | Apple Orange Apple 那么, 下面的文字中有几个Apple呢? 没有几分钟数不出来吧? 而且容易数错。 这样的问题交给计算机回答再适合不过了。 | ORANGE Banana APPLE Banana BANANA Apple BANANA Apple BANANA Apple | APPLE Apple ORANGE Apple ORANGE Orange ORANGE Orange ORANGE Banana | APPLE Banana BANANA Banana ORANGE Orange BANANA Apple APPLE Banana | BANANA Banana APPLE Banana ORANGE Orange ORANGE Banana APPLE Orange | BANANA Orange BANANA Banana APPLE Banana BANANA Orange APPLE Orange | APPLE Orange BANANA Banana ORANGE Banana ORANGE Banana BANANA Apple | APPLE Orange ORANGE Orange BANANA Banana BANANA Apple ORANGE Orange | ORANGE Banana APPLE Orange BANANA Orange APPLE Banana APPLE Banana | ORANGE Banana ORANGE Banana ORANGE Banana BANANA Apple BANANA Banana | ORANGE Apple APPLE Apple APPLE Orange APPLE Apple APPLE Apple BANANA | Banana BANANA Banana APPLE Banana BANANA Banana APPLE Orange ORANGE | Banana APPLE Orange BANANA Orange APPLE Orange BANANA Banana ORANGE | Banana BANANA Apple ORANGE Banana ORANGE Apple ORANGE Banana APPLE | Apple APPLE Orange ORANGE Orange APPLE Apple APPLE Orange BANANA | Banana ORANGE Apple ORANGE Orange ORANGE Banana ORANGE Apple APPLE | Apple ORANGE Banana BANANA Banana APPLE Apple APPLE Banana APPLE Apple | APPLE Banana APPLE Orange BANANA Orange BANANA Apple BANANA Apple | APPLE Banana ORANGE Apple APPLE Apple BANANA Banana ORANGE Apple | ORANGE Apple ORANGE Banana APPLE Orange BANANA Apple ORANGE Orange | APPLE Apple ORANGE Orange BANANA Banana BANANA Orange BANANA Banana | APPLE Apple ORANGE Orange APPLE Banana ORANGE Banana BANANA Orange | BANANA Banana BANANA Apple BANANA Banana APPLE Orange BANANA Orange | ORANGE Apple APPLE Banana APPLE Banana ORANGE Orange APPLE Apple APPLE | Orange APPLE Orange ORANGE Orange BANANA Orange BANANA Banana BANANA | Orange ORANGE Banana BANANA Apple ORANGE Orange BANANA Orange APPLE | Apple BANANA Banana BANANA Banana APPLE Apple APPLE Orange BANANA | Apple BANANA Orange BANANA Apple BANANA Apple ORANGE Banana ORANGE | Orange BANANA Banana APPLE Orange BANANA Banana ORANGE Apple ORANGE | Apple BANANA Banana APPLE Apple APPLE Banana ORANGE Banana APPLE | Banana APPLE Banana APPLE Apple BANANA Apple ORANGE Banana APPLE Apple | BANANA Orange ORANGE Banana ORANGE Apple APPLE Banana APPLE Apple | APPLE Banana APPLE Orange ORANGE Orange ORANGE Banana ORANGE Orange | APPLE Orange APPLE Banana ORANGE Apple APPLE Apple ORANGE Apple ORANGE | Apple ORANGE Apple APPLE Banana APPLE Apple BANANA Orange BANANA Apple | BANANA Apple BANANA Orange APPLE Banana ORANGE Apple APPLE Apple APPLE | Apple APPLE Apple BANANA Orange ORANGE Orange ORANGE Banana APPLE | Apple BANANA Apple ORANGE Apple BANANA Banana APPLE Orange BANANA | Banana APPLE Orange ORANGE Apple BANANA Orange ORANGE Apple APPLE | Banana APPLE Banana BANANA Banana ORANGE Apple APPLE Orange BANANA | Orange APPLE Banana ORANGE Banana APPLE Banana BANANA Banana APPLE | Orange APPLE Apple APPLE Banana ORANGE Orange APPLE Orange ORANGE | Banana BANANA Orange ORANGE Banana ORANGE Banana BANANA Orange BANANA | Orange ORANGE Banana BANANA Banana APPLE Orange APPLE Orange APPLE | Orange APPLE Orange ORANGE Apple BANANA Orange BANANA Banana BANANA | Orange BANANA Banana ORANGE Banana BANANA Apple APPLE Orange BANANA | Banana ORANGE Banana BANANA Orange APPLE Orange BANANA Apple APPLE | Banana ORANGE Orange ORANGE Apple APPLE Orange APPLE Apple ORANGE | Apple APPLE Banana APPLE Banana APPLE Banana ORANGE Banana ORANGE | Apple BANANA Apple BANANA Banana ORANGE Orange ORANGE Apple APPLE | Banana BANANA Banana BANANA Orange ORANGE Apple APPLE Apple APPLE | Apple BANANA Orange ORANGE Banana ORANGE Apple ORANGE Banana APPLE | Banana APPLE Apple APPLE Orange ORANGE Apple APPLE Apple APPLE Orange | ORANGE Orange APPLE Banana BANANA Apple ORANGE Orange BANANA Banana | ORANGE Apple APPLE Orange APPLE Banana APPLE Apple APPLE Banana BANANA | Banana APPLE Orange APPLE Banana ORANGE Orange ORANGE Banana ORANGE | Apple ORANGE Orange ORANGE Orange ORANGE Banana APPLE Banana BANANA | Banana APPLE Banana APPLE Banana BANANA Banana ORANGE Orange BANANA | Banana ORANGE Orange ORANGE Orange APPLE Apple ORANGE Apple APPLE | Orange BANANA Orange BANANA Apple ORANGE Banana BANANA Orange ORANGE | Banana BANANA Apple APPLE Apple BANANA Banana BANANA Orange APPLE | Apple ORANGE Banana BANANA Orange BANANA Apple BANANA Apple APPLE | Banana ORANGE Banana APPLE Orange APPLE Orange APPLE Orange BANANA | Orange BANANA Orange APPLE Orange APPLE Orange APPLE Banana BANANA | Banana APPLE Orange ORANGE Banana APPLE Banana ORANGE Orange APPLE | Apple BANANA Orange APPLE Orange APPLE Orange ORANGE Banana BANANA | Orange BANANA Apple APPLE Banana BANANA Banana BANANA 编程就是将 **现实中的问题** 转化成 **计算机可以理解的问题** 的过程。 词频统计器需求_ .. _词频统计器需求: http://lanlab.org/course/2019s/python/requirements.html 程序员是这个转化者。 转化是艰辛的工作。 但是由于一旦程序写好, 就可以重复利用, 所以这种辛苦是值得的。 所以, 重复性的劳动就交由计算机去做吧。 而程序员要做的是读懂问题, 分析好问题, 写好指令, 把指令存在程序中, 然后让计算机执行程序。 清晰的代码很重要, 如果代码不清晰, 维护代码将是一场噩梦, 很多时候代码索性就无法维护。 在整个程序的生命周期中, 维护的花销最大 (举冰山的例子)。 程序也有生命, 如果程序停止维护, 它的生命基本上就结束了。 没有人会对不再被维护的程序很感兴趣。 因为不再维护了, 就意味的失去了改善的可能性。 编程的要件是 **数据** ,以及 **对数据的操作** 。 不管是什么程序, 一般来说会有一个输入, 一个输出, 输入与输出之间就是一系列的运算。 我们要确保输入是正确有效的, 输出是我们期望的结果, 运算是有效率的。 例子1 .. code:: python a = 10 # 输入1 b = 2 # 输入2 print(a**b) # a的b次方是输出 100 例子2 .. code:: python a = 'hello' # 输入1 b = ' word' # 输入2 print(a + b) # a + b表示将两个字符串合并在一起 以上的输入是我们写进程序中的,其实我们还可以在命令行中输入, 利用 input 函数。 实际编程中, 手动从命令行输入数值的情况比较少。 熟练的程序员比较常用的是利用命令行参数来输入数据。 .. code:: python a = int(input('Enter a: ')) b = int(input('Enter b: ')) print(a**b) 字符串用来存储信息。 是个最基本的数据类型。 日常生活中, 你发的短信就是一个字符串。 一篇文章, 不论多少字,说到底,也是一个字符串。 我们可以对字符串进行多种多样的操作,以达到我们的具体目的。 关于字符串的一系列问题。 问题: 如何存储一个字母 a? .. code:: python a = 'a' 问题: a 与 'a'有什么区别? a是变量名。 'a'是值。 a = 'a' 这个语句要从右边向左边读, 即把'a'这个值赋给变量a。 我们可以用其他任何有效的变量名, 比如c就很好。 单引号很重要, 如何没有单引号, a就是变量。 在使用变量前要先对它赋值。 赋值后内存中就会存有这个变量。 .. code:: python a = 'a' # 把字符’a‘赋值给变量a, 此时内存中有变量a, 我们可以在下面的语句中使用它 c = a # 把变量a中的值赋给变量c, 这时c的值与a的值是一样的,都是'a' print(a == c) # 为什么这里有两个等于号呢? 问题: 变量名只能由一个字母组成吗? 起一个有效的变量名。 | i | j | k | v | name | amount | price | number 变量可以起到帮助别人理解程序的作用, 所以变量的名字要起得尽量有意义。 要么简洁, 要么有意义。 问题: 如何存储一个单词 apple? .. code:: python fruit = 'apple' 问题: 将apple全部转大写。 .. code:: python fruit = 'apple' print(fruit.upper()) 问题: 如何知道fruit对应的值的长度? .. code:: python l = len(fruit) # fruit对应的值有几个字符 print(l) 以上l是个变量, len是函数名, 功能是数出fruit变量对应的值有几个字符。 问题: 如何存储两个单词 apple banana? .. code:: python fruit = 'apple banana' 问题: 这时候fruit的长度是多少? 请你数一数。 问题: apple 中有字母b吗? 简单的 .. code:: python 'b' in 'apple' 复杂的 .. code:: python fruit = 'apple' result = False for c in fruit: if c == 'b': result = True print(result) 问题: apple 中有字符串app吗? .. code:: python 'app' in 'apple' 问题: 水果字符串中有橘子orange吗? .. code:: python fruit = 'apple banana apple' print('orange' in fruit) 问题: 如何数 apple 中有几个 p? 简单的 .. code:: python fruit.count('p') 复杂的 .. code:: python fruit = 'apple' count = 0 for c in fruit: if c == 'p': count += 1 print(count) 问题: 数出字符串'apple banana apple'中, apple出现的次数? .. code:: python fruit = 'apple banana apple' print(fruit.count('apple')) 问题: 如何获得第一个p出现的位置? .. code:: python fruit = 'apple' position = fruit.find('p') print(position) 问题: 我现在一头雾水, 这正常吗? 总是出错, 这正常吗? 这很正常。 编程要达到一定的代码量, 才能渐渐感觉清晰。 你的第一个目标是100行代码, 实现这个目标后下一个目标是500行代码, 当你的代码量超过1000行时, 很多问题会渐渐清晰。 出错也很正常, 认识到错误的原因, 把错误改正了, 就等于进步了。 **练习** 以脚本模式运行下面的程序, 查看输出结果。 脚本模式即把下面的代码存在文件fruit.py中, 然后在命令行运行python fruit.py。 .. code:: python lst = [ 'apple', 'orange', 'banana' ] num = 3 # 多少个水果 import random s = '' for i in range(num): w = random.choice(lst) # 随机在lst中选一个元素 if i % 3 == 0: # 百分号%代表模 s += ' ' + w.upper() if i % 3 == 1: s += ' ' + w.title() if i % 3 == 2: s += ' ' + w fruit = s.strip() print(fruit) fruit中有多少apple? 有多少banana? 有多少orange? 数的时候你需要区分大小写吗? (难度加大) 找出控制水果数的变量, 改变其值, 产生100个水果。 (难度再加大) 今后,我们将统计每个水果出现的次数。 你不会编程, 但是你可以用文字的方式写下解决这个问题的思路。 (难度再加大) 今后,我们也会将结果排序, 比如按照水果出现的次数从高到低来排序, 或者按照水果的名字来排序(按照字典序)。 (代码重用) 这样的程序是不是也可以用来统计一篇文章中所有单词的词频? 进而帮助我们学习英文? **练习** 把下面这段文字转成字符串并存在变量boris中。 Boris Johnson, Prime Minister of the United Kingdom. Alexander Boris de Pfeffel Johnson is a British politician serving as Prime Minister of the United Kingdom and Leader of the Conservative Party since July 2019. He has been the Member of Parliament for Uxbridge and South Ruislip since 2015 and was the MP for Henley from 2001 to 2008. He also served as Mayor of London from 2008 to 2016 and Foreign Secretary from 2016 to 2018. Johnson identifies as a one-nation conservative and has been associated with both economically and socially liberal policies. 将本段文本中所有字符转成大写字母。 JOHNSON共出现了几次? 这段文本中共有多少字符? 其中标点符号占了几个字符? 空格占了几个字符? 最简单的类定义 ------------------------------------ class A: pass 以上面的类为蓝本,创建一个实例:a = A()。 虽然这个a什么也做不了。 Python脚本文件命令行执行 -------------------------------------- python a.py。 函数头的三要素 --------------------------------------- def,函数名,参数列表: | def add_number(a, b): | return a + b | def add_lst(a, b): | if len(a) != len(b): | return 'ERROR: a and b not in equal length.' | n = len(a) | result = [] | for i in range(n): | result.append(a[i] + b[i]) | return result | | print( add_lst([1,2,3],[-1,-2,-3]) ) Python的关键词 -------------------------------- | def pass | from import | False True | in | None | class | return | while for | continue break | and or not | if else elif | try except finally raise | lambda nonlocal | del global with | yield assert | as is 关键词被语言留用(reserved),无法作变量名。 值的类型 ------------------------- 所有的值都是对象。a = 5, help(a) a.bit_length() 数字。1, 1.,1.1, .1, 1e1, 1e-1, 1E1, 1E-1 字符串(string)。'hello', 100 * 'hello', 'hello' * 100, 'Weight is %4.2f kg' % (70.2) f = open('a.html') s = f.read() f.close() 列表(list)。['a', 'b', 'c', 'd'] ['bob', 170, 'john', '180'] [1, 2, 3, 4] range(10) 返回一个range对象。可以用list函数把这个对象变成列表。 等价的是range(0, 10, 1),从0开始,步进1,不包括10。 A list of list A list of tuples A list of objects 元组(tuple),字典(dict)。 变量(Variable) ------------------------------------ 是一个名字(name),是指向一个值(value)的名字。 值存放在内存(memory)中的某个地址。 尽量选有意义的简短的名字。比如,代表个数用n,代表索引用i,j,k。 关键词不能用作变量名。 值存放在内存某处。值会记录指向它的变量个数。 为节省空间,如果几个变量的值相同,那么这些变量有时会指向这个值(而不是为每个变量单独分配内存空间单独存放该值)。 这叫做interning技术。但并非总是如此。 | a = 10 | b = 10 | c = 10 | id(a), id(b), id(c) | (8791229060416, 8791229060416, 8791229060416) 值10存在地址8791229060416,所有a,b,c三个变量都指向(point to)这个地址。 | x = 257 | y = 257 | id(x), id(y) | (46487024, 46487952) 以上虽然变量x与y的值都是一样,可是这两个值存放在不同的内存地址。 | s1 = 'hello' | s2 = 'hello' | id(s1), id(s2) | s1 == s2 | s1 is s2 | s1 = 'h' * 100 | s2 = 'h' * 100 | id(s1), id(s2) | s3 = 'hello, world!' | s4 = 'hello, world!' | id(s3), id(s4) | (46703536, 46705136) | class A: | pass | a = A() | b = A() | a | <__main__.A object at 0x0000000002CD92E8> | b | <__main__.A object at 0x0000000002CD9240> | x = [1,2,3] | id(x) | 46869512 | y = x | id(y) | 46869512 | x.append(4) | x | [1, 2, 3, 4] | y | [1, 2, 3, 4] | x = [] | id(x) | 46869640 | x = [1,2,3,4] | y = [1,2,3,4] | id(x) | 46869768 | id(y) | 46868808 一个没有名字与之对应的值将会被清出内存。 参考资料: - http://foobarnbaz.com/2012/07/08/understanding-python-variables/ - https://stackoverflow.com/questions/19721002/is-a-variable-the-name-the-value-or-the-memory-location 可变(mutable)类型与不可变类型 ---------------------------------------------------------- 字符串是不可变的(immutable)类型,不能在原内存地址改变。 a = 'hello' 不可以原地修改a[0] = 'H'。需要修改a的值时,需要对a进行重新赋值a = 'Hello'。 列表是可变(mutable)类型,能在原内存地址改变。 a = [1, 2] 可以原地修改a[0] = 2 参考资料: - https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types 表达式(expression):值,变量或操作符的组合。 | 17 | n + 2 语句(statement):能够制造一个变量或者显示信息的代码。 | n = 17 | print(n) 数与格式化显示 ------------------------- | x = 3.1415926 | print('%4.0f' % (x)) | print('%4.1f' % (x)) | print('%4.2f' % (x)) | print('%4.3f' % (x)) | print('%4.4f' % (x)) | print('%6.0f' % (x)) | print('%6.1f' % (x)) | print('%6.2f' % (x)) | print('%6.3f' % (x)) | print('%6.4f' % (x)) | print('%.0f' % (x)) | print('%.1f' % (x)) | print('%.2f' % (x)) | print('%.3f' % (x)) | print('%.4f' % (x)) | print('%.5f' % (x)) | print('%.6f' % (x)) | print('%.7f' % (x)) | print('%.8f' % (x)) | print('%.9f' % (x)) | print('%.15f' % (x)) | print('%.16f' % (x)) | print('%.17f' % (x)) | print('%.18f' % (x)) | print('%4.f' % (x)) | print('%5.f' % (x)) | print('%6.f' % (x)) | print('%7.f' % (x)) | print('%8.f' % (x)) | print('%f' % (x)) 字符串(Strings) ------------------------------------------ 由字符组成。 | fruit = 'banana!' | first_letter = fruit[0] | second_letter = fruit[1] 索引(index)从0开始,所以1代表第二个字符。只用整数。 负整数代表从字符串末尾开始。如fruit[-1]代表fruit字符串最后一个字符。 | i = 1 | fruit[i] | fruit[i+1] len()函数。返回字符串字符个数。len(fruit)。 | L = len(fruit) | fruit[L-1],最后一个字符。与fruit[-1]等价。 遍历(traverse)字符串。 | fruit = 'banana' | for c in fruit: | print(c) 反向遍历。 | fruit = 'banana' | for i in range(len(fruit)-1,-1,-1): | print(fruit[i]) | fruit = 'banana' | for c in fruit[::-1]: # [start,stop,step] | print(c) | fruit = 'banana' | for c in ''.join(reversed(fruit)): | print(c) 以上 ``# [start,stop,step]`` 代表注释(comment),注释以 ``#`` 号开头。 字符串相加(concatenation) ------------------------------------------------------- 输出Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack | prefixes = 'JKLMNOPQ' | suffix = 'ack' | for c in prefixes: | if c == 'O' or c == 'Q': | print(c + 'u' + suffix) | else: | print(c + suffix) 子串(slice) ------------------------------------------------------- s[n:m],其中n或m可省略。 包括第n个字符,不包括第m个字符。(索引自0开始) | s = 'Monty Python' | s[0:5] | s[6:12] | s[:5] | s[6:] | s[:] n一般小于m。如果n大于等于m,那么就返回空字符串。 空字符串的长度是0。 字符串是immutable的。不能改变已有的字符串。 | greeting = 'Hello, world!' | greeting[0] = 'J' | greeting = 'Hello, world!' | new_greeting = 'J' + greeting[1:] 搜索字符串 ----------------------------- | def find(word, c): | i = 0 | while i < len(word): | if word[i] == c: | return i | i = i + 1 | return -1 | print(find('banana', 'a')) 练习一:加第三个参数,设定从哪个字符开始搜起。 练习二:加第三个参数,设定从哪个方向开始搜起。 String对象有内置函数find。 数字符串中某个字符的个数。 练习:用上面三参数的find来做。 String类(对象)方法 ------------------------------------------ | upper() | lower() 方法调用:invocation/call | word.find('na') | word.find('na', 3) | name.find('b', 1, 2) in操作符 ------------------------------------------ 'a' in 'banana' 'seed' in 'banana' 练习:写出下面的函数,使得 in_both('apples', 'oranges')返回'aes'。 字符串比较 ------------------------------------------- 字典序(alphabetical order)。大写字母排在小写字母前。 字符串之间可以有以下对比操作: | == | >, >= | <, <= 练习:写is_reverse函数,使得is_reverse('god', 'dog')返回True。 find_from函数的两种实现。如果能够找出错误,给1分奖励。 字符串是对象(object)。 对象的本质涵义 - data construct。 计算复杂度。 即兴定义函数,制造一个长度不小于4的密码。 列表 -------------------- 语言的内置(built-in)类型。注意与String类比,index也是从0开始, in操作符, 求长度,获得字串,遍历操作类似。 | [ ] | [10, 20, 30, 40] | ['crunchy frog', 'ram bladder', 'lark vomit'] 列表中的元素不需要是同一类型的: ``['spam', 2.0, 5, [10, 20]]`` 列表[10,20]在另外一个列表中,这叫嵌套列表。 ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]],长度是多少? 列表是 Mutable类型。值可以在原地变。(注意与String的区别)。 IndexError 遍历 for cheese in cheeses: print(cheese) for i in range(len(numbers)): numbers[i] = numbers[i] * 2 for x in []: print('This never happens.') .. 讨论软件工程认证数据输入问题。 ``+`` 操作符用来连接, ``*`` 操作符用来重复。 列表的方法 append extend sort t = ['d', 'c', 'e', 'b', 'a'] t.sort() # 问t.sort()返回什么值? t sum - reduce方法,把几个值变成一个值 map方法,把几个值变成另外几个值 def f(x): return 2*x list(map(f, [1,2])) filter方法,从几个值中选择符合条件的几个值。 | def f(x): | if x % 2 == 0: | return True | return False | list(filter(f, [1,2,3,4])) pop | t = ['a', 'b', 'c'] | x = t.pop(1) # pop可不带参数,不带参数返回哪个值? del | t = ['a', 'b', 'c'] | del t[1] | t = ['a', 'b', 'c', 'd', 'e', 'f'] | del t[1:5] remove | t = ['a', 'b', 'c'] | t.remove('b') split | list_of_characters = list('spam') | list_of_words = 'spam should be filtered'.split() | list_of_words = 'spam-should-be-filtered'.split('-') join方法 | ','.join(['1','2','3']) | a = 'banana' | b = 'banana' | a is b # a与b是不是指向同一个值 | a == b | a = [1, 2, 3] | b = [1, 2, 3] | a is b # not identical, a and b are not the same object | a == b # equivalent though they have the same values 别名(Aliasing) a = [1, 2, 3] b = a b is a 把变量名与对象联系起来叫做reference。 a与b是指向[1,2,3]的两个references。 因为[1,2,3]是mutable的,所以使用a对[1,2,3]做改变同样影响到b对应的值。 error-prone(易错) 列表作为参数 --------------------------------------------- | def delete_head(t): | del t[0] | letters = ['a', 'b', 'c'] | delete_head(letters) # letters and t points to the same list object. | letters 注意区别 ``append`` 与 ``+`` 操作符 ---------------------------------------------- | t1 = [1, 2] | t2 = t1.append(3) | t1 | [1, 2, 3] | t2 | t3 = t1 + [4] | t3 | [1, 2, 3, 4] | t1 | [1, 2, 3] 区别如下两个函数: def bad_delete_head(t): t = t[1:] # WRONG! def tail(t): return t[1:] TDD - Test-driven Development ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 测试驱动开发。 My favourite。 刺激有挑战性。 帮助厘清需求。 帮助编写代码。 推荐使用pytest。如何安装? 使用命令 ``pip install pytest``。 在 ``test_cases.py`` 写如下测试用例。然后在命令行运行: ``python -m pytest test_cases.py`` 。 .. code:: python # Copyright (c) Hui Lan 2019 import random import string def make_password(n): ''' Return a string of length n consisting of a combination of letters, digits and special characters. Note that each password must have at least one lower case letter, one upper case letter, one digit and one special charater. Return an empty string if n is less than 4. ''' if n < 4: return '' password = random.choice(string.ascii_lowercase) + \ random.choice(string.ascii_uppercase) + \ random.choice(string.digits) + \ random.choice(string.punctuation) + \ ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for i in range(n-4)]) return ''.join(random.sample(password, n)) # shuffle password then return if __name__ == '__main__': for n in range(0,20): pwd = make_password(n) print(pwd) 计算复杂度 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 用Big O表述复杂度。O(n), O(n^2), O(n^3)。 密码实验回顾。 字典(Dictionary) --------------------------------- Mutable数据类型。 实际开发中超级有用。 | d = {} or d = dict() | d = {'hot':'热', 'cool':'凉', 'cold':'冷'} | d['warm'] = '温' | d['warm'] | d['freezing'] # KeyError | len(d) | 'warm' in d | '温' in d.values() key value key-value pair (item) item的顺序不可预测,不是按照创建时的顺序。 递增开发(Incremental Development) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 每次完成一小点。从易到难。 练习:给定一个字符串,数出每个字母出现的频率。 .. code:: python def histogram(s): ''' Cannot pass any test cases. ''' pass def histogram(s): ''' Can pass the test case in which s is an empty string. ''' d = {} return d def histogram(s): ''' Can pass the test cases in which all characters in s are unique. ''' d = {} for c in s: d[c] = 1 return d def histogram(s): ''' Can pass all test cases. ''' d = {} for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d h = histogram('good') print(h) 练习:给定一个字符串,数出每个单词出现的频率。 练习:给定一个新闻文本,数出每个单词出现的频率。考虑以下方面,(1)只考虑字典里有的单词。(2)单词周围如有标点符号,要先移除。 .. code:: python # Copyright (C) 2019 Hui Lan # The following line fixes SyntaxError: Non-UTF-8 code starting with ... # coding=utf8 def file2lst(fname): ''' Return a list where each element is a word from fname. ''' L = [] f = open(fname) for line in f: line = line.strip() lst = line.split() for x in lst: L.append(x) f.close() return L def lst2dict(lst): ''' Return a dictionary given list lst. Each key is an element in the lst. The value is always 1.''' d = {} for w in lst: d[w] = 1 return d import string def remove_punctuation(s): p = ',.:’“”' + string.punctuation t = '' for c in s: if not c in p: t += c elif c == '’': # handle the case such as May’s return t return t def word_frequency(fname, english_dictionary): ''' Return a dictionary where each key is a word both in the file fname and in the dictionary english_dictionary, and the corresponding value is the frequency of that word.''' d = {} L = file2lst(fname) for x in L: x = remove_punctuation(x.lower()) if x in english_dictionary: if not x in d: d[x] = 1 else: d[x] += 1 return d def sort_by_value(d): ''' Return a sorted list of tuples, each tuple containing a key and a value. Note that the tuples are order in descending order of the value.''' import operator lst = sorted(d.items(), key=operator.itemgetter(1), reverse=True) return lst if __name__ == '__main__': ed = lst2dict(file2lst('words.txt')) # from http://greenteapress.com/thinkpython2/code/words.txt d = word_frequency('brexit-news.txt', ed) lst = sort_by_value(d) for x in lst: print('%s (%d)' % (x[0], x[1])) 练习: 改写函数 ``word_frequency`` , 使它能接受第三个参数, ``black_lst``。 ``black_lst`` 是包含要排除考虑的单词的列表。 例如, ``black_lst`` 可以是 ``['the', 'and', 'of', 'to']`` 。 key与value互换 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 注意到在原来的字典中一个value可能对应多个key的值。比如 ``d = {'a':1, 'b':2, 'c':2}`` 中,2就对应两个key,'b'与'c'。 .. code:: python def inverse_dictionary(d): d2 = {} for k in d: v = d[k] if not v in d2: d2[v] = [k] else: d2[v].append(k) return d2 d = {'a':1, 'b':2, 'c':2} d2 = inverse_dictionary(d) print(d2) 练习: 用 ``inverse_dictionary`` 对上面 ``d = word_frequency('brexit-news.txt', ed)`` 产生的 ``d`` 进行转化。然后按照单词出现频率从高到低把所有单词都显示出来。每行显示一个频率内的所有单词。 .. code:: python d2 = inverse_dictionary(d) for k in sorted(d2.keys(), reverse=True): print('%d %s' % (k, ' '.join(d2[k]))) 练习: 使用 ``setdefault`` 方法对上面的 ``inverse_dictionary`` 进行简化 (减少行数)。 .. code:: python def inverse_dictionary(d): d2 = {} for k in d: v = d[k] d2.setdefault(v, []).append(k) return d2 字典里面可以有字典 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python d = { 'john':{'dob':'1990-10-23', 'height':'6 feet 5 inches'} } 函数 ------ 当我们开始不断复制黏贴代码时,就要考虑把这部分代码做成函数了。 函数 ``unique_words`` 与 ``unique_words2`` 哪个运行速度快? .. code:: python def unique_words(lst): d = {} for x in lst: d[x] = 1 return sorted(d.keys()) def unique_words2(lst): return sorted(list(set(lst))) N = 10000000 print(unique_words(['hello', 'world', 'am', 'he'] * N)) print(unique_words2(['hello', 'world', 'am', 'he'] * N)) 局部变量 ~~~~~~~~~~~~~~~~ 在函数之内。函数执行结束,局部变量消失。 全局变量 ~~~~~~~~~~~~~~~~ 全局变量位于函数之外,模块之内。全局变量对所有模块内的函数可见(可读)。如果在函数内要对全局变量重新赋值,那么要先用 ``global`` 声明之 (declare)。 .. code:: python verbose = True def example1(): if verbose: print('Running example1') def example2(): verbose = False # a NEW local variable verbose if verbose: print('Running example2') def example3(): global verbose # I am actually going to use the global variable verbose; don't create a local one. verbose = False if verbose: print('Running example3') print(verbose) example1() print(verbose) example2() example1() print(verbose) example3() example1() print(verbose) 全局的列表与字典,如果只需改变其内容,而不是重新赋值,则不需要用 ``global`` 声明。 .. code:: python record = {'s1':65, 's2':60} def add_score(student, score): record[student] = score print(record) add_score('s3', 75) print(record) 练习: 定义一个函数 ``empty_dict`` 清空字典 ``record``。 要求: 不能用 ``return`` 语句。 提示: 可以用 ``pop`` 方法, 或者直接给 ``record`` 赋值 ``{}`` 。 调用函数与传递参数 ~~~~~~~~~~~~~~~~~~~~~~~~~ 在使用函数前要先确定函数已经被定义。 区别 ``argument`` 与 ``parameter`` 。传过去的是 ``argument`` , 函数头的参数列表是 ``parameter`` 。 ``argument`` 的值赋给 ``parameter`` , ``parameter`` 是函数的局部变量。 ``argument`` 与 ``parameter`` 的名字可以相同也可以不同。 .. code:: python def reverse_string(s): t = '' for i in range(len(s)-1,-1,-1): t += s[i] return t s = 'put' t = reverse_string(s) print(t) 以上 s 一个是全局变量一个是局部变量。 以上 t 一个是全局变量一个是局部变量。 函数执行顺序 (flow of execution) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 函数的定义不执行,被调用时才执行。 顺序执行。 当遇到函数调用时,跳转到函数,执行函数,函数返回后继续执行跳转地后一条语句。 文件 ------------------------------------------------ 信息多存储在文件中。所以文件的读写是最最常见的操作。 本节主要考虑纯文本文件。 以下后缀结尾的文件一般都是纯文本文件: txt, csv, html, rst, md。 实验: 读取纽约新生儿的名字统计文件 PopularBabyNames_ 。 写命令行程序 lookupname.py 。给定性别与种族,输出最流行的头几个名字。 命令行例子: ``python lookupname.py girl white top5`` 。 这个命令输出最流行的5个白人女孩的名字。 第一个参数可以是 ``girl/boy`` , 第二个参数可以是 ``asian/white/black/hispanic`` 。第三个参数以 ``top`` 开始,默认是 1。 .. _PopularBabyNames: https://data.cityofnewyork.us/api/views/25th-nujf/rows.csv?accessType=DOWNLOAD .. code:: python # Copyright (C) 2019 Hui Lan # lanhui AT zjnu.edu.cn # Purpose: 1. Introduce command line argument parsing. 2. Introduce nested dictionaries. # Usage: # python lookupname.py asian boy top10 # python lookupname.py white girl top5 # python lookupname.py girl white top def map(x): d = {'FEMALE':'girl', 'MALE':'boy', 'ASIAN AND PACIFIC ISLANDER':'asian', 'ASIAN AND PACI':'asian', 'BLACK NON HISPANIC':'black', 'BLACK NON HISP':'black', 'HISPANIC':'hispanic', 'WHITE NON HISPANIC':'white', 'WHITE NON HISP':'white'} return d[x] def file2dict(fname): d = {} # will be a nested dictionary: e.g., d[gender] = {'asian':{'name':count}, 'black':[], 'white':[], 'hispanic':[]} f = open(fname) lines = f.readlines() for line in lines[1:]: line = line.strip() lst = line.split(',') gender = map(lst[1]) ethnicity = map(lst[2]) firstname = lst[3].title() count = int(lst[4]) if not gender in d: d[gender] = {ethnicity: {firstname:count}} else: if not ethnicity in d[gender]: d[gender][ethnicity] = {firstname:count} else: if not firstname in d[gender][ethnicity]: d[gender][ethnicity][firstname] = count else: d[gender][ethnicity][firstname] += count f.close() return d def get_commandline_parameter(lst): d = {'gender':'', 'ethnicity':'', 'top':1} for x in lst: o = x.lower() if o in ['asian', 'black', 'white', 'hispanic']: d['ethnicity'] = o elif o in ['girl', 'boy']: d['gender'] = o elif o == 'top': pass # use default value 1 elif 'top' in o: d['top'] = int(o[3:]) else: raise Exception('Not recognised option %s' % (x)) return d def sort_by_value(d): ''' Return a sorted list of tuples, each tuple containing a key and a value. Note that the tuples are order in descending order of the value.''' import operator lst = sorted(d.items(), key=operator.itemgetter(1), reverse=True) return lst import sys if __name__ == '__main__': d = file2dict('Popular_Baby_Names.csv') args = get_commandline_parameter(sys.argv[1:]) gender = args['gender'] ethnicity = args['ethnicity'] top = args['top'] d2 = d[gender][ethnicity] lst = sort_by_value(d2) for i in range(top): print(lst[i][0]) 模块 ----------------------------------------------- 每个py文件就是一个模块。 每个模块有一个隐含的变量指示模块名, ``__name__`` 。 当该py文件作为主模块运行时, ``__name__`` 的值是 ``__main__`` 。 当该py文件作为被引入的模块时,该模块的 ``__name__`` 的是模块名 (是文件名)。 在每个py文件 ``if __name__ == '__main__':`` 后添加测试代码, 当这个py文件作为主模块运行时,测试代码会被执行。 而当引入这个py文件时,该文件的测试代码不会被执行,我们也不希望它们执行。 排序 ------------------------------------------------ 排序是常见重要的操作。 按照成绩排序。 按照文件名排序。 按照文件大小排序。 按照时间排序。 Python自带的 ``sorted`` 可以很好满足排序需求。 排序一组数或一组字符串 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 如果需要从大到小排序, 添加 ``reverse=True`` 。 .. code:: python # Sort numbers import random a = [random.randint(0,100) for i in range(5)] # a list of 5 random numbers between 0 and 100 print(a) sa_incr = sorted(a) print(sa_incr) sa_decr = sorted(a, reverse=True) print(sa_decr) # Sort a list of strings s = 'D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation. https://d3js.org/' lst = list(set(s.split())) sa_incr = sorted(lst) print(sa_incr) sa_decr = sorted(lst, reverse=True) print(sa_decr) 自定义排序算法 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 为了弄清排序的原理, 我们看两种排序算法。 选择排序 ``````````````````````````````````````````````````` 遍历列表,每次把最小的那个放到最左边位置。 .. code:: python # Copyright (C) 2019 Hui Lan # lanhui AT zjnu.edu.cn def swap(L, i, j): L[j], L[i] = L[i], L[j] def selection_sort(L): i = 0 while i < len(L): min_val = L[i] k = j = i while j < len(L): if L[j] < min_val: min_val = L[j] k = j j += 1 swap(L, i, k) # will change L i += 1 return L if __name__ == '__main__': import random for n in range(10): a = [random.randint(0,100) for i in range(n)] sa = selection_sort(a) print(sa) assert sa == a assert sa == sorted(a) 合并排序 (Merge sort) ``````````````````````````````````````````````````` 将列表一分为二,对每半部分排序,把排好序的两部分合并之(确保合并后同样是排好序的)。 注意到,以下的实现方式是递归。 .. code:: python # Copyright (C) 2019 Hui Lan # lanhui AT zjnu.edu.cn def _merge(L, R): ''' Return a sorted list that combines the sorted list L and sorted list R.''' nL = len(L) nR = len(R) result = [] i = j = count = 0 while count < nL + nR: if i >= nL and j < nR: result.append(R[j]) j += 1 elif j >= nR and i < nL: result.append(L[i]) i += 1 elif L[i] < R[j]: result.append(L[i]) i += 1 else: result.append(R[j]) j += 1 count += 1 return result def merge_sort(L): if len(L) <= 1: return L else: i = int(len(L)/2) l = merge_sort(L[:i]) r = merge_sort(L[i:]) return _merge(l, r) if __name__ == '__main__': import random for n in range(100): a = [random.randint(0,100) for i in range(n)] sa = merge_sort(a) assert sa == sorted(a) 比较排序速度 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 排序是 Python 的核心算法,所以是优化了再优化。 Python 自带的排序算法最快, ``selection_sort`` 最慢。 .. code:: python from merge_sort import merge_sort from selection_sort import selection_sort import random, time L = [random.randint(0,10000) for i in range(10000)] print('Python sort ...') now = time.time() result0 = sorted(L) print(time.time() - now) print('Merge sort ...') now = time.time() result1 = merge_sort(L) print(time.time() - now) print('Selection sort ...') now = time.time() result2 = selection_sort(L) print(time.time() - now) assert result0 == result1 assert result1 == result2 在命令行运行上面的程序,在作者的计算机上得到如下的结果。 | Python sort ... | 0.002 | Merge sort ... | 0.083 | Selection sort ... | 11.57 排序元组列表 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 一个元组由多个元素组成,多个元组组成元组列表, 如何按照某个元素进行排序呢? 可以有以下两种方案。一种用模块 ``operator`` , 一种用 ``lambda`` 函数。 .. code:: python def sort_by_nth_element(lst, n): ''' Return a sorted list of tuples lst, according to the nth element in each tuple.''' import operator result = sorted(lst, key=operator.itemgetter(n)) return result def sort_by_nth_element2(lst, n): ''' Return a sorted list of tuples lst, according to the nth element in each tuple.''' result = sorted(lst, key=lambda x: x[n]) # https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda return result if __name__ == '__main__': lst = [(1, 'xxx', 2), (2, 'aaa', 1)] print(sort_by_nth_element(lst, 0)) print(sort_by_nth_element(lst, 1)) print(sort_by_nth_element(lst, 2)) print(sort_by_nth_element2(lst, 0)) print(sort_by_nth_element2(lst, 1)) print(sort_by_nth_element2(lst, 2)) 巧用 lambda 函数进行灵活排序 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 如何把一个由字符串组成的列表按照字符串的长短进行排序? .. code:: python lst = ['this', 'is', 'a', 'example'] a = sorted(lst, key=lambda x: len(x)) b = sorted(lst, key=lambda x: -len(x)) print('\n'.join(a)) s = '''https://genius.com/William-shakespeare-romeo-and-juliet-act-1-prologue-annotated#note-2756596 Romeo and Juliet PROLOGUE Two households, both alike in dignity, In fair Verona, where we lay our scene, From ancient grudge break to new mutiny, Where civil blood makes civil hands unclean. From forth the fatal loins of these two foes A pair of star-cross'd lovers take their life; Whose misadventured piteous overthrows Doth with their death bury their parents' strife. The fearful passage of their death-mark'd love, And the continuance of their parents' rage, Which, but their children's end, nought could remove, Is now the two hours' traffic of our stage; The which if you with patient ears attend, What here shall miss, our toil shall strive to mend.''' lst = s.split('\n') c = sorted(lst, key=lambda x: len(x)) d = sorted(lst, key=lambda x: -len(x)) print('\n'.join(c)) 以上程序运行会输出如下结果。 :: a is this example PROLOGUE Romeo and Juliet Two households, both alike in dignity, Whose misadventured piteous overthrows In fair Verona, where we lay our scene, From ancient grudge break to new mutiny, The which if you with patient ears attend, And the continuance of their parents' rage, Is now the two hours' traffic of our stage; Where civil blood makes civil hands unclean. From forth the fatal loins of these two foes A pair of star-cross'd lovers take their life; The fearful passage of their death-mark'd love, Doth with their death bury their parents' strife. What here shall miss, our toil shall strive to mend. Which, but their children's end, nought could remove, https://genius.com/William-shakespeare-romeo-and-juliet-act-1-prologue-annotated#note-2756596 递归 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Memo `````````````````````````````````````````````````` .. code:: python def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) known = {0:0, 1:1} def fibonacci_memo(n): ''' A 'memoized' version of fibonacci. ''' if n in known: return known[n] res = fibonacci(n-1) + fibonacci(n-2) known[n] = res return res n = 35 import time t1 = time.time() print(fibonacci(n)) print('%4.2f' % (time.time() - t1)) t1 = time.time() print(fibonacci_memo(n)) print('%4.2f' % (time.time() - t1)) 用递归方式改写 ``selection_sort`` ``````````````````````````````````````````````````` .. code:: python def selection_sort(L): if len(L) <= 1: return L min_val = L[0] k = j = 0 while j < len(L): if L[j] < min_val: min_val = L[j] k = j j += 1 L[k], L[0] = L[0], L[k] return [min_val] + selection_sort(L[1:]) 注意以上的代码在L的长度很大(1000可以,10000不可以)的时候会用尽所有stack。 类 class 与 对象 object ------------------------------------------------------------------ 程序员用类(class)来定义一类数据。 .. code:: python class Point: """Represents a point in 2-D space.""" blank = Point() blank.x = 1 # an attribute blank.y = 2 # an attribute x = blank.x def print_point(p): print('(%g, %g)' % (p.x, p.y)) def reset_point(p): # object is Mutable p.x = 0 p.y = 0 print_point(blank) reset_point(blank) print_point(blank) blank 是(指向) Point类型的对象的一个变量。 注意到Point后面跟随了括 号, 是对类的实例化 (instantiation)。 我们说 blank 是Point类的一个实 例 (instance), 也可以说是Point类的一个对象。 对象是Mutable类型数据。 如 reset_point 所示。 一个对象可以是另外一个对象的属性 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '(%g, %g)' % (self.x, self.y) class Rectangle: def __init__(self, lower_left_corner, width, height): self.lower_left_corner = lower_left_corner # lower_left_corner is a Point object self.width = width self.height = height def get_center(self): return Point(self.lower_left_corner.x + self.width/2, self.lower_left_corner.y + self.height/2) class Circle: def __init__(self, center, radius): self.center = center # center is a Point object self.r = radius r = Rectangle(Point(0,0), 10, 4) print(r.get_center()) copy 与 deepcopy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ copy 拷贝类中的属性, 但不会重新制作一个对象中的对象 (embedded object),而是拷贝其引用而已。 而deepcopy会。 .. code:: python import copy class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return '(%g, %g)' % (self.x, self.y) def __eq__(self, other): return self.x == other.x and self.y == other.y class Rectangle: def __init__(self, lower_left_corner, width, height): self.lower_left_corner = lower_left_corner # lower_left_corner is a Point object self.width = width self.height = height p1 = Point(1, 2) p2 = copy.copy(p1) print(p1 is p2) print(p1 == p2) # what if we don't have the __eq__ method r1 = Rectangle(Point(0,0), 10, 4) r2 = copy.copy(r1) print(r1 is r2) # False print(r1.lower_left_corner is r2.lower_left_corner) # True print(r1.width is r2.width) # also True r1.width = 20 print(r1.width is r2.width) print(r2.width) # remain to be 10 r1 = Rectangle(Point(1,1), 8, 4) r3 = copy.deepcopy(r1) print(r1 is r3) # False print(r1.lower_left_corner is r2.lower_left_corner) # False 纯函数与修改函数 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 纯函数(pure function)。 修改函数(modifier function)。 .. code:: python class Time: def __init__(self, h, m, s): self.hour = h self.minute = m self.second = s def __str__(self): return '%02d:%02d:%02d' % (self.hour, self.minute, self.second) def time_to_seconds(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def seconds_to_time(seconds): time = Time(0, 0, 0) minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time def increment_time_pure(t, h, m, s): ''' Pure function ''' secs = time_to_seconds(t) + time_to_seconds(Time(h, m, s)) return seconds_to_time(secs) def increment_time_modifier(t, h, m, s): ''' Modifier function ''' t.hour += h t.minute += m t.second += s def increment_time_modifier2(t, h, m, s): ''' Modifier function ''' t.second += s if t.second > 59: minute_from_seconds, t.second = divmod(t.second, 60) t.minute += m + minute_from_seconds if t.minute > 59: hour_from_minutes, t.minute = divmod(t.minute, 60) t.hour += h + hour_from_minutes t = Time(6, 58, 55) print(t) ti = increment_time_pure(t, 2, 30, 50) print(ti) increment_time_modifier(t, 2, 30, 50) print(t) print(seconds_to_time(time_to_seconds(t))) **Designed development** . 先有总体设计,然后再有开发。比如先把时间转成秒,再把秒转成时间(hh:mm:ss)。 **Prototype and patch** . 先造个原型,如果有问题,逐步修改。 类中的方法,就是在类中的函数定义。对方法的调用与对函数的调用不同。 对方法的调用我们用点操作符(dot notation)。点前面是对象,点后面是方法。 调用类方法 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python class Time: def __init__(self, h, m, s): self.hour = h self.minute = m self.second = s def print_time(self): print( '%02d:%02d:%02d' % (self.hour, self.minute, self.second) ) def print_time2(time): print( '%02d:%02d:%02d' % (time.hour, time.minute, time.second) ) t = Time(1, 30, 20) Time.print_time(t) Time.print_time2(t) t.print_time() t.print_time2() 练习:在Time类中添加一个方法 time_to_seconds,把时间转换成秒。 练习:在Time类中添加一个方法, is_after, 返回True/False。 练习:在Time类中添加一个方法, __add__, 使得我们可以用加号相加两个时间。 如果是一个时间加上一个整数呢? 或者是一个整数加上一个时间呢? 提示:使用isinstance,__radd__。 方法中可以定义函数 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python class Time: def __init__(self, h, m, s): self.hour = h self.minute = m self.second = s def time_to_seconds(self): minutes = self.hour * 60 + self.minute seconds = minutes * 60 + self.second return seconds def increment_time(self, seconds): def seconds_to_hhmmss(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) return hours, minutes, seconds self.hour, self.minute, self.second = seconds_to_hhmmss(self.time_to_seconds() + seconds) def __str__(self): return '%02d:%02d:%02d' % (self.hour, self.minute, self.second) t = Time(1, 30, 20) print(t) t.increment_time(3600) print(t) 在t.increment_time(3600)中, t叫做subject。 接口与实现相分离。 Positional argument. Keyword argument. .. code:: python class Time: def __init__(self, h, m=0, s=0): self.hour = h self.minute = m self.second = s def __str__(self): return '%02d:%02d:%02d' % (self.hour, self.minute, self.second) t = Time(1) print(t) t = Time(1, s=20) print(t) t = Time(1, m=30) print(t) t = Time(1, 30, 20) print(t) 多态 (polymorphism) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 如果函数可以对多个类型使用,我们把它叫做多态函数。 如histogram,可以对字符串使用去数里面字符的频率, 也可以对列表使用去数里面元素的频率。 如系统自带的sum函数。 sum([1, 2, 3]), sum([Time(1,0,0), Time(0,1,0), Time(0,0,1)])。 .. code:: python def time_to_seconds(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def seconds_to_time(seconds): time = Time(0, 0, 0) minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time class Time: def __init__(self, h=0, m=0, s=0): self.hour = h self.minute = m self.second = s def __add__(self, other): if isinstance(other, Time): return seconds_to_time( time_to_seconds(self) + time_to_seconds(other) ) else: return seconds_to_time( time_to_seconds(self) + other ) def __radd__(self, other): return self.__add__(other) def __str__(self): return '%02d:%02d:%02d' % (self.hour, self.minute, self.second) print(sum([Time(1,0,30), Time(0,0,30), Time(0,59,0)])) 继承(inheritance) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 继承用于从父类(parent)中继承属性与方法,创建一个子类 (child)。 如果 子类中的方法与父类中的方法同名, 则在子类实例中用子类定义的方法 (overrride)。 利于代码重用。 缺点是代码不易读懂。 并不是非要代码重用 不可。 类关系图(class diagram)。 两类关系, HAS-A 与 IS-A 。 HAS-A 。 长方形中有点。 IS-A 。 一手牌是一副牌。 .. code:: python class A: def __init__(self, a): self.a = a def __str__(self): return 'Parent string method.' class B(A): pass class C(A): def __init__(self, a, b): super().__init__(a) self.b = b x = B(2) print(x) y = C(2, 3) print(y) 扑克牌。Card 类, Deck 类, Hand(Deck) 类继承 Deck 类。 Hand 是一手牌, 可以用 Deck 中的拿牌与出牌。 类属性(class attribute)与实例属性(instance attribute)。 .. code:: python """This module contains a code example related to Think Python, 2nd Edition by Allen Downey http://thinkpython2.com Copyright 2015 Allen Downey License: http://creativecommons.org/licenses/by/4.0/ """ import random class Card: """Represents a standard playing card. Attributes: suit: integer 0-3 rank: integer 1-13 """ suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"] rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank def __str__(self): """Returns a human-readable string representation.""" return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) def __eq__(self, other): """Checks whether self and other have the same rank and suit. returns: boolean """ return self.suit == other.suit and self.rank == other.rank def __lt__(self, other): """Compares this card to other, first by suit, then rank. returns: boolean """ t1 = self.suit, self.rank t2 = other.suit, other.rank return t1 < t2 class Deck: """Represents a deck of cards. Attributes: cards: list of Card objects. """ def __init__(self): """Initializes the Deck with 52 cards. """ self.cards = [] for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) def __str__(self): """Returns a string representation of the deck. """ res = [] for card in self.cards: res.append(str(card)) return '\n'.join(res) def __len__(self): return len(self.cards) def add_card(self, card): """Adds a card to the deck. card: Card """ self.cards.append(card) def remove_card(self, card): """Removes a card from the deck or raises exception if it is not there. card: Card """ self.cards.remove(card) def pop_card(self, i=-1): """Removes and returns a card from the deck. i: index of the card to pop; by default, pops the last card. """ return self.cards.pop(i) def shuffle(self): """Shuffles the cards in this deck.""" random.shuffle(self.cards) def sort(self): """Sorts the cards in ascending order.""" self.cards.sort() def move_cards(self, hand, num): """Moves the given number of cards from the deck into the Hand. hand: destination Hand object num: integer number of cards to move """ for i in range(num): hand.add_card(self.pop_card()) class Hand(Deck): """Represents a hand of playing cards.""" def __init__(self, label=''): self.cards = [] self.label = label if __name__ == '__main__': deck = Deck() deck.shuffle() hand = Hand() deck.move_cards(hand, 5) hand.sort() print(hand) hand.move_cards(deck, 5) .. _UseSqlite.py: 用于数据库操作。以 SQLite 为例子 (UseSqlite.py)。 .. code:: python # Reference: Dusty Phillips. Python 3 Objected-oriented Programming Second Edition. Pages 326-328. # Copyright (C) 2019 Hui Lan import sqlite3 class Sqlite3Template: def __init__(self, db_fname): self.db_fname = db_fname def connect(self, db_fname): self.conn = sqlite3.connect(self.db_fname) def instructions(self, query_statement): raise NotImplementedError() def operate(self): self.results = self.conn.execute(self.query) # self.query is to be given in the child classes self.conn.commit() def format_results(self): raise NotImplementedError() def do(self): self.connect(self.db_fname) self.instructions(self.query) self.operate() class InsertQuery(Sqlite3Template): def instructions(self, query): self.query = query class RiskQuery(Sqlite3Template): def instructions(self, query): self.query = query def format_results(self): output = [] for row in self.results.fetchall(): output.append(', '.join([str(i) for i in row])) return '\n'.join(output) if __name__ == '__main__': #iq = InsertQuery('RiskDB.db') #iq.instructions("INSERT INTO inspection Values ('FoodSupplies', 'RI2019051301', '2019-05-13', '{}')") #iq.do() #iq.instructions("INSERT INTO inspection Values ('CarSupplies', 'RI2019051302', '2019-05-13', '{[{\"risk_name\":\"elevator\"}]}')") #iq.do() rq = RiskQuery('RiskDB.db') rq.instructions("SELECT * FROM inspection WHERE inspection_serial_number LIKE 'RI20190513%'") rq.do() print(rq.format_results()) Web 应用程序 --------------------------------------------------- 我们将使用 Flask 这个 Python 微型框架来实现网页应用程序。 在文本框输入文本 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 利用 Flask 库中的 request 实现前端与后端的信息传递。 前端是网页, 我们需要形成一个网页 (静态的, 动态的, 手工写的, 模版 形成的)。 我们在前端的文本框中输入数据, 希望把数据传给后端的 Python 程序处理。 如何实现这一点? 靠 request 。 用 from flask import Flask, request 先把 request 这个模块引入。 .. code:: html
Enter a risk ...
以上这段存成一个html文件, 注意到这里我们没有涉及到任何python代码, 打 开就是一个表格, 当我们点击按钮 Enter 后, 在程序运行时, 输入框 company_name, serial_number, risk_detail 中的信息会被 request.form 存 储。 在Python程序中可以用 request.form['companay_name'] 来得到用户实际 在文本框中输入的信息。 信息可小可大, 小的比如一个数字, 大的比如一段 文本。 信息一旦提取, 我们就像平时在非网络环境下一样, 处理这段信息。 解释 method="post" 。 解释 action="/enter" 。 以下是完整的程序 risk.py , 特别注意 enter() 那个函数。 UseSqlite 模块已经 由上文 `UseSqlite.py`_ 定义。 在命令行输入 python risk.py 然后在 Firefox打开 127.0.0.1:5000 这个网址即可运行。 在 Firefox 地址栏输入 127.0.0.1:5000/enter 这个地址并按回车键时, 就会 运行 enter() 中 else 那段代码, 这叫 GET 一个网页, 其实就是返回了一个 有html tag的字符串给 Firefox, 以便 Firefox 正确显示。 在按下 Enter 按 钮后, 就会运行 enter() 中 if 那段代码, 这是 POST 一个网页后执行的操 作, 添加数据到数据库中。 .. code:: python from flask import Flask, request from UseSqlite import InsertQuery, RiskQuery from datetime import datetime import json app = Flask(__name__) def make_html_table_row(s): lst = s.split(',') index = s.find('{') result = 'Risk information for all companies
Search risks ...
' page += '' return page @app.route("/enter", methods=['GET', 'POST']) def enter(): if request.method == 'POST': # when we submit a form company_name = request.form['company_name'] if company_name == '': return 'Company name required.' serial_number = request.form['serial_number'] if serial_number == '': return 'Serial number required.' risk_detail = request.form['risk_detail'] if risk_detail == '': return 'Risk_detail information required.' date = datetime.now().strftime('%Y-%m-%d') iq = InsertQuery('RiskDB.db') iq.instructions("INSERT INTO inspection Values ('%s', '%s', '%s', '%s')" % (company_name, serial_number, date, risk_detail)) iq.do() return 'You have entered the following information:
%s - %s - %s
Enter a risk ...
\n' page += '' return page @app.route("/") def mainpage(): page = '' page += '' page += get_database_records() return page if __name__ == '__main__': app.run(debug=True) 上传文件 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ omg 其它有用的Python语言特性 ---------------------------------------------------- 条件表达 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 把 if else 写在一行。看函数 take_log3。 .. code:: python import math def take_log(x): if x > 0: return math.log(x) else: raise Exception('The input is not a positive number.') def take_log2(x): if x > 0: return math.log(x) else: return float('nan') def take_log3(x): return math.log(x) if x > 0 else float('nan') x = -1 try: result = take_log(x) print('result from take_log is %g.' % (result)) except: print('x is not a good value. ') result = take_log2(x) print('result from take_log2 is %g.' % (result)) result = take_log3(x) print('result from take_log3 is %g.' % (result)) Generator表达 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Generator也是一个对象,对象里面有 __iter__ 与 __next__ 方法。 当所有的元素都遍历完之后,抛出 **StopIteration** 异常。 .. code:: python g = (x**2 for x in range(3)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) 可以用 for loop 遍历 g 中的所有元素。 .. code:: python g = (x**2 for x in range(3)) for x in g: print(x) any 与 all ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ any/all 是个函数,可以接收 list 或 generator 类型的参数。 .. code:: python any([False, False, True]) # True developed_countries = ['canada', 'germany', 'japan', 'uk', 'swiss', 'norway'] f = open('brexit-news.txt') news = f.read() f.close() print( any(word.strip().lower() in developed_countries for word in news.split()) ) print( all(word.strip().lower() in developed_countries for word in news.split()) ) 集合 Sets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python set('123') set([1,2,3]) def all_letters_unique(word): return len(set(word)) == len(word) def all_letters_vowel(word): return set(word) <= set('aeiou') def compare_vocaburary(a, b): return set(a) > set(b) def vocaburary_diff(a, b): return list(set(a) - set(b)) def vocaburary_common(a, b): return list(set(a).intersection(set(b))) print( all_letters_unique('unique') ) print( all_letters_vowel('ou') ) print( compare_vocaburary(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) ) print( vocaburary_diff(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) ) print( vocaburary_common(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) ) 计数 Counter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 与字典有点像。 .. code:: python from collections import Counter c = Counter('donald') # Counter({'d': 2, 'o': 1, 'n': 1, 'a': 1, 'l': 1}) c['d'] # 2 c['x'] # 0, not a KeyError c.most_common() # [('d', 2), ('o', 1), ('n', 1), ('a', 1), ('l', 1)] vote = Counter(['yes', 'no', 'yes', 'yes', 'no']) # Counter({'yes': 3, 'no': 2}) defaultdict ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 可以避免第一次加 value 时 key 不再引起的 KeyError。 .. code:: python from collections import defaultdict def seperate_odd_and_even(lst): d = defaultdict(list) # the factory is list for x in lst: if x % 2 != 0: d['odd'].append(x) else: d['even'].append(x) return d def unique_odd_and_even(lst): d = defaultdict(set) # the factory is set for x in lst: if x % 2 != 0: d['odd'].add(x) else: d['even'].add(x) return d result = seperate_odd_and_even([1,2,3,4,5]) result['odd'] result['even'] result2 = unique_odd_and_even([1,1,2,2,3,3]) result2['odd'] result2['even'] 收集keyword args ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: python def printall(*args, **kwargs): print(args) # args is a tuple print(kwargs) # kwargs is a dictionary printall(1,2,3, a=1,b=2,c=3) 利用第三方库函数 pillow --------------------------------------------------- 我们希望建立一个私人相册, 需要通过编程实现缩略图(thumbnail)。 为此,利用第三方提供的库 pillow 。 .. code:: python from PIL import Image import os # details: https://pillow.readthedocs.io/en/stable/reference/Image.html#examples def make_thumbnail(picture_fname, size): image = Image.open(picture_fname) image.thumbnail((size,size), Image.ANTIALIAS) fname, fext = os.path.splitext(picture_fname) image.save(fname + '_small.jpg') image.close() make_thumbnail('ottawa.jpg', 200) 以上代码定义了一个函数 make_thumbnail, 可以帮任何图片生成缩略图。 哈希表 (hash table) --------------------------------------------------------- 参见书本 Think Python 2e 第 B.4 节以及相应的代码 http://thinkpython2.com/code/Map.py 。 参考 ------ - Think Python 2e – Green Tea Press. http://greenteapress.com/thinkpython2/thinkpython2.pdf. .. Make a html page from this file. Issue the following command: pip install docutils && rst2html.py LectureNotesOnPython.rst LectureNotesOnPython.html