-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnote
More file actions
76 lines (52 loc) · 1.97 KB
/
note
File metadata and controls
76 lines (52 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
print语句输出传给它的表达式的值。
尾部的逗号可以避免输出换行符:
4.更多的控制流工具
4.7.2。 关键字参数
4.7.3.任意参数列表 ?
4.7.4.开箱参数列表 ?
4.7.5. lambda表达式
In [2]: def incre(n):
...: return lambda x: x + n
...:
In [3]: f = incre(42)
In [4]: f(0)
Out[4]: 42
In [5]: f(2)
Out[5]: 44
4.7.6. 文档字符串 pass
4.8.间奏曲: 编码样式 pass
chapter 5 数据结构
5.1. 深入list(列表)
5.1.1. 用list(列表)作为stack(栈) zhan
5.1.2. 用list(列表)作为queue(队列)
5.1.3.函数式编程工具
在使用列表时有三个函数非常有用:filter()、map()和reduce()。
5.1.4. 列表推导式
例如,假设我们想要创建一个列表 squares:
>>>
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
我们可以用下面的方式得到同样的结果:
squares = [x**2 for x in range(10)]
这也相当于squares = map(lambda x: x**2, range(10)),但是更简洁和易读。
列表推导式由括号括起来,括号里面包含一个表达式,表达式后面跟着一个for语句,后面还可以接零个或更多的for或if语句。结果是一个新的列表,由表达式依据其后面的for和if子句上下文计算而来的结果构成。例如,下面的 listcomp 组合两个列表中不相等的元素:
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
它等效于:
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
注意在两个代码段中for 和 if 语句的顺序是相同的。
如果表达式是一个元组(例如前面示例中的 (x, y)),它必须带圆括号。
5.1.4.1. 嵌套的列表推导式
lock here
https://yiyibooks.cn/yy/python_278/tutorial/controlflow.html