update
many, many chore
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# 阶段五:迭代生成
|
||||
|
||||
# 前言
|
||||
## 前言
|
||||
|
||||
在写乘法表的时候,你可能写过类似
|
||||
|
||||
@@ -18,13 +18,13 @@ for (int i = 0; i < n; i ++)
|
||||
|
||||
但是,你想过 Python 在处理 for in 语句的时候,具体发生了什么吗?什么样的对象可以被 for in 来枚举呢?
|
||||
|
||||
# 容器迭代
|
||||
## 容器迭代
|
||||
|
||||
容器这个概念非常好理解。
|
||||
|
||||
在 Python 中一切皆对象,对象的抽象就是类,而对象的集合就是容器。
|
||||
|
||||
列表(list: [0, 1, 2]),元组(tuple: (0, 1, 2)),字典(dict: {0:0, 1:1, 2:2}),集合(set: set([0, 1, 2]))都是容器。
|
||||
列表`list: [0, 1, 2]`,元组`tuple: (0, 1, 2)`,字典`dict: {0:0, 1:1, 2:2}`,集合`set: set([0, 1, 2])`都是容器。
|
||||
|
||||
对于容器,你可以很直观地想象成多个元素在一起的单元;而不同容器的区别,正是在于内部数据结构的实现方法。
|
||||
|
||||
@@ -74,11 +74,11 @@ StopIteration
|
||||
[1, 2, 3, 4]
|
||||
```
|
||||
|
||||
# 英语练习,对迭代器的类比
|
||||
## 英语练习,对迭代器的类比
|
||||
|
||||
<strong>Analogy</strong>: An iterable is like a book (one can flip through the pages) and an iterator for a book would be a bookmark (saves the position and can locate the next page). Calling `iter` on a book gives you a new bookmark independent of other bookmarks, but calling `iter` on a bookmark gives you the bookmark itself, without changing its position at all. Calling `next` on the bookmark moves it to the next page, but does not change the pages in the book. Calling `next` on the book wouldn't make sense semantically. We can also have multiple bookmarks, all independent of each other.
|
||||
|
||||
# 生成器:懒人迭代器!
|
||||
## 生成器:懒人迭代器!
|
||||
|
||||
```python
|
||||
def test_iterator():
|
||||
@@ -114,7 +114,8 @@ Wall time: 12.5 s
|
||||
|
||||
声明一个迭代器很简单,[i for i in range(100000000)]就可以生成一个包含一亿元素的列表。每个元素在生成后都会保存到内存中,你通过代码可以看到,它们占用了巨量的内存,内存不够的话就会出现 OOM 错误。
|
||||
|
||||
了解下 yield()函数吧,他可以返回一个生成器对象,试试看懂这个
|
||||
::: warning 🤔 了解下 yield()函数吧,他可以返回一个生成器对象,试试看懂这个
|
||||
:::
|
||||
|
||||
```python
|
||||
>>> def gen_list(lst):
|
||||
@@ -133,7 +134,7 @@ Wall time: 12.5 s
|
||||
StopIteration
|
||||
```
|
||||
|
||||
# 思考题:python 会显示什么?为什么?
|
||||
## 思考题:python 会显示什么?为什么?
|
||||
|
||||
```python
|
||||
>>> s = [1, 2, 3, 4]
|
||||
@@ -185,9 +186,9 @@ ______
|
||||
______
|
||||
```
|
||||
|
||||
# 任务
|
||||
## 任务
|
||||
|
||||
P10:实现 `count`,它接受一个迭代器 `t` 并返回该值 `x` 出现在 的第一个 n 个元素中的次数 `t`
|
||||
P10:实现 `count`,它接受一个迭代器 `t` 并返回该值 `x` 出现在的前 n 个元素中的次数 `t`
|
||||
|
||||
```python
|
||||
def count(t, n, x):
|
||||
|
||||
Reference in New Issue
Block a user