1 深入条件控制
小记:编程风格
- 使用 4 空格缩进,而非 TAB:在小缩进(可以嵌套更深)和大缩进(更易读)之间,4空格是一个很好的折中。TAB 引发了一些混乱,
- 使用空行分隔函数和类,以及函数中的大块代码,可能的话,注释独占一行
- 把空格放到操作符两边,以及逗号后面,但是括号里侧不加空格:a = f(1, 2) + g(3, 4)
- 统一函数和类命名:推荐类名用 驼峰命名, 函数和方法名用 小写_和_下划线。
- Python 的默认情况下,UTF-8最好
while 和 if 语句中使用:比较和包含。
比较操作符 in 和 not in 审核值是否在一个区间之内。
比较操作可以传递。例如 a < b == c 审核是否 a 小于 b 并且 b 等于 c。
逻辑操作符 and 和 or 组合,not 具有最高的优先级, or 优先级最低,所以 A and not B or C 等于 (A and (notB)) or C。
逻辑操作符 and 和 or 参数从左向右解析,结果确定就停止。例如,如果 A 和 C 为真而 B 为假, A and B and C 不会解析 C。
可以把比较或其它逻辑表达式的返回值赋给一个变量,例如:
|
1
2
3
4
|
>>> string1, string2, string3 = ‘‘, ‘Trondheim‘, ‘Hammer Dance‘>>> non_null = string1 or string2 or string3>>> non_null‘Trondheim‘ |
解释:and 和 or 参数从左向右解析,结果确定就停止。string1 or string2 为True,打印string2是值,后面忽略即string3。
比较序列和其它类型:序列对象可以与相同类型的其它对象比较。
首先比较前两个元素,如果不同,就决定了比较的结果;如果相同,就比较后两个元素,依此类推,直到所有序列都完成比较。
|
1
2
3
4
5
6
|
>>> (1,3,67)<(1,4,2)True>>> (1,3,67)>(1,4,2)False>>> [1, 2, 3] < [1, 2, 4]True |
如果两个元素本身就是同样类型的序列,就递归字典序比较。如果两个序列的所有子项都相等,就认为序列相等。
|
1
2
|
>>> (1, 2, 3) == (1.0, 2.0, 3.0)True |
如果一个序列是另一个序列的初始子序列,较短的一个序列就小于另一个。字符串的字典序按照单字符的 ASCII 顺序。
|
1
2
3
4
|
>>> (1, 2) < (1, 2, -1)True>>> (1, 2, (‘aa‘, ‘ab‘)) < (1, 2, (‘abc‘, ‘a‘), 4)True |
2 基本的列表对象方法
List列表基本操作概要:
list.append(x):元素添加到链表的结尾,相当于 a[len(a):] = [x]。
list.extend(L):给定列表所有元素添加,相当于 a[len(a):] = L。
list.insert(i, x):指定位置插入。其中list.insert(0, x)=插入链表首,list.insert(len(a), x)=list.append(x)=插入链表尾
list.remove(x):删除链表指定元素。
list.pop([i]):指定索引下删除元素,a.pop() 返回最后一个元素。
list.clear():删除所有元素。相当于 del a[:]。
list.index(x):返回链表首个值 x 的索引。
list.count(x):统计元素 x出现的次数。
list.sort():排序。
list.reverse():倒排链表。
list.copy():浅拷贝。等同于 a[:]。
操作运行代码:
|
1
2
3
4
5
6
7
8
9
10
11
|
a = [66.25, 333, 333, 1, 1234.5]print(a.count(333), a.count(66.25), a.count(‘x‘))a.insert(2, -1)a.append(333)[66.25, 333, -1, 333, 1, 1234.5, 333]a.index(333)a.remove(333)a.reverse()[333, 1234.5, 1, 333, -1, 66.25]a.sort()a.pop() |
List链表的多重共用
链表当作堆栈用:链表特性先进后出跟堆栈性质一致,进:append,出:pop:
程序实例演示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> stack = [3, 4, 5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7>>> stack[3, 4, 5, 6]>>> stack.pop()6>>> stack[3, 4,5] |
链表当作队列使用:如上演示,知道链表具备先进后出的性质,即符合堆栈性质。大家记得否链表索引可以为负数,如此你是不是想到先进先出啦?对喽,这就是队列的性质我们完全可以当着队列用。列表这样用效率不高。在头部插入和弹出很慢,因为一个元素出队,要移动整个列表中的所有元素。要实现队列,使用 集合collections.deque,它为在首尾两端快速插入和删除而设计。例如:
程序运行实例:
|
1
2
3
4
5
6
7
8
9
10
|
>>> from collections import deque>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry") # Terry arrives>>> queue.append("Graham") # Graham arrives>>> queue.popleft() # The first to arrive now leaves‘Eric‘>>> queue.popleft() # The second to arrive now leaves‘John‘>>> queue # Remaining queue in order of arrivaldeque([‘Michael‘, ‘Terry‘, ‘Graham‘]) |
列表推导:如下实例快速解析理解
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> [(user,name) for user in [‘bnc‘,‘ad‘,‘admin‘] for name in [‘boy‘,‘xiaoming‘,‘bnc‘,‘admin‘] if user==name][(‘bnc‘, ‘bnc‘), (‘admin‘, ‘admin‘)]等同>>> combs = []>>> for user in [‘bnc‘,‘ad‘,‘admin‘]:... for name in [‘boy‘,‘xiaoming‘,‘bnc‘,‘admin‘]:... if user == name:... combs.append((user, name))...>>> combs[(‘bnc‘, ‘bnc‘), (‘admin‘, ‘admin‘)]>>> # call a method on each element>>> freshfruit = [‘ banana‘, ‘ loganberry ‘, ‘passion fruit ‘]>>> [weapon.strip() for weapon in freshfruit][‘banana‘, ‘loganberry‘, ‘passion fruit‘] |
链表做文本处理矩阵计算:交换行列
#由三个长度为 4 的列表组成的 3x4 矩阵,交换行列
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
>>> matrix = [... [1, 2, 3, 4],... [5, 6, 7, 8],... [9, 10, 11, 12],... ]>>> [[row[i] for row in matrix] for i in range(4)][[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]等于>>> transposed = []>>> for i in range(4):... transposed.append([row[i] for row in matrix])...>>> transposed[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
3 del语句
del语句:不同于有返回值的 pop() 方法,其按索引来删除子项
|
1
2
3
4
5
6
7
8
9
10
|
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4] # 切片>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[] |
4 元组、序列、集合和字典
元组和列表的区别:
元组:不同种类元素,不可变;
列表:相同种类的元素,可变
|
1
2
3
4
5
6
7
8
9
|
>>> t = 12345, 54321, ‘hello!‘>>> t[0]12345>>> t(12345, 54321, ‘hello!‘)>>> # Tuples may be nested:... u = t, (1, 2, 3, 4, 5)>>> u((12345, 54321, ‘hello!‘), (1, 2, 3, 4, 5)) |
set集合
特点:set集合是无序不重复元素的集。
基本功能:关系测试和消除重复元素。还支持 union(联合),intersection(交),difference(差)和 sysmmetric difference(对称差集)等数学运算。
集合创建:大括号或 set() 函数。注意:空集合的创建必须使用 set() 而不是 {}。{}可以用于创建空字典。
集合实例演示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
>>> basket = {‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘}>>> print(basket) # show that duplicates have been removed{‘orange‘, ‘banana‘, ‘pear‘, ‘apple‘}>>> ‘orange‘ in basket # fast membership testingTrue>>> ‘crabgrass‘ in basketFalse>>> # Demonstrate set operations on unique letters from two words>>> a = set(‘abracadabra‘)>>> b = set(‘alacazam‘)>>> a # unique letters in a{‘a‘, ‘r‘, ‘b‘, ‘c‘, ‘d‘}>>> a - b # letters in a but not in b{‘r‘, ‘d‘, ‘b‘}>>> a | b # letters in either a or b{‘a‘, ‘c‘, ‘r‘, ‘d‘, ‘b‘, ‘m‘, ‘z‘, ‘l‘}>>> a & b # letters in both a and b{‘a‘, ‘c‘}>>> a ^ b # letters in a or b but not both{‘r‘, ‘d‘, ‘b‘, ‘m‘, ‘z‘, ‘l‘} |
类似 列表推导式,这里有一种集合推导式语法:
|
1
2
3
|
>>> a = {x for x in ‘abracadabra‘ if x not in ‘abc‘}>>> a{‘r‘, ‘d‘} |
字典
字典以 关键字 为索引,关键字可以是任意不可变类型,通常用字符串或数值。字典本质是无序键值对 (key:value 对)集合,同一字典内键必须是互不相同的。
字典创建: {} 。
主要操作:据键存储和析取值。可用 del 来删除键:值对(key:value)。
排序: sorted(d.keys()) )。
检查字典:用 in 关键字检查字典中是否存在某个关键字。
字典实例演示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
>>> tel = {‘jack‘: 4098, ‘sape‘: 4139}>>> tel[‘guido‘] = 4127>>> tel{‘sape‘: 4139, ‘guido‘: 4127, ‘jack‘: 4098}>>> tel[‘jack‘]4098>>> del tel[‘sape‘]>>> tel[‘irv‘] = 4127>>> tel{‘guido‘: 4127, ‘irv‘: 4127, ‘jack‘: 4098}>>> list(tel.keys())[‘irv‘, ‘guido‘, ‘jack‘]>>> sorted(tel.keys())[‘guido‘, ‘irv‘, ‘jack‘]>>> ‘guido‘ in telTrue>>> ‘jack‘ not in telFalse |
dict() 构造函数可以直接从 key-value 对中创建字典:
|
1
2
3
4
5
6
7
8
9
10
|
>>> dict([(‘sape‘, 4139), (‘guido‘, 4127), (‘jack‘, 4098)]){‘sape‘: 4139, ‘jack‘: 4098, ‘guido‘: 4127}>>> dict(sape=4139, guido=4127, jack=4098){‘sape‘: 4139, ‘jack‘: 4098, ‘guido‘: 4127}>>> tel={x:x**2 for x in range(2,12,3)}>>> list(tel.keys())[8, 2, 11, 5]>>> sorted(tel.keys())[2, 5, 8, 11] |
5 循环技巧
字典循环,关键字和对应的值可以使用 items() 方法同时解读出来:
|
1
2
3
4
5
6
|
>>> knights = {‘gallahad‘: ‘the pure‘, ‘robin‘: ‘the brave‘}>>> for k, v in knights.items():... print(k, v)...gallahad the purerobin the brave |
在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到:
|
1
2
3
4
5
|
>>> for i, v in enumerate([‘tic‘, ‘tac‘, ‘toe‘]):print(i, v)0 tic1 tac2 toe |
同时循环两个或更多的序列,可以使用 zip() 整体打包:
|
1
2
3
4
5
6
7
|
>>> questions = [‘name‘, ‘quest‘, ‘favorite color‘]>>> answers = [‘lancelot‘, ‘the holy grail‘, ‘blue‘]>>> for q, a in zip(questions, answers):print(‘What is your {0}? It is {1}.‘.format(q, a))What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue. |
需要逆向循环序列的话,先正向定位序列,然后调用 reversed() 函数:
|
1
2
3
4
5
6
7
|
>>> for i in reversed(range(1, 10, 2)):print(i)97531 |
要按排序后的顺序循环序列的话,使用 sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:
|
1
2
3
4
5
6
7
|
>>> basket = [‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘]>>> for f in sorted(set(basket)):print(f)applebananaorangepear |
若要在循环内部修改正在遍历的序列(例如复制某些元素),建议您首先制作副本。在序列上循环不会隐式地创建副本。切片表示法使这尤其方便:
|
1
2
3
4
5
6
7
|
>>> words = [‘cat‘, ‘window‘, ‘defenestrate‘]# Loop over a slice copy of the entire list.>>> for w in words[:]:if len(w) > 6:words.insert(0, w)>>> words[‘defenestrate‘, ‘cat‘, ‘window‘, ‘defenestrate‘] |
6 参考文献和推荐资料
- Python 官方网站 :包含代码、文档和 Web 上与 Python 有关的页面链接该网站镜像于全世界的几处其它问题,类似欧洲、日本和澳大利亚。镜像可能会比主站快,这取决于你的地理位置
- 快速访问 Python 的文档
- Python 包索引 :索引了可供下载的,用户创建的 Python 模块。如果你发布了代码,可以注册到这里,这样别人可以找到它
- The Scientific Python : 项目包括数组快速计算和处理模块,和大量线性代数、傅里叶变换、非线性solvers、随机数分布,统计分析以及类似的包
- 官方python学习文档
- 简明Python教程
- 廖雪峰:python教程
- Python官网文档
- 【51cto学院,入门课程】Python零基础入门学习视频教程
- 【个人博客:案例】GitHub数据提取与分析
- 【csdn】python知识库
- 【社区】python中文学习大本营
- 【个人博客】老王python
-
【51cto学院】如何用python开发跨平台的记事本视频课程
-
【51cto学院,网站开发】台湾辅仁大学:Python Django基础视频课程
-
【51cto学院,网站开发】用Python Django快速做出高大上的BBS论坛网站
标签:eth 有序 需要 数据结构 注册 fas abc repr 基础入门
原文地址:https://www.cnblogs.com/franson-2016/p/8325496.html