|
5 | 5 | ---------- |
6 | 6 | 问题 |
7 | 7 | ---------- |
8 | | -todo... |
| 8 | +你想将一个多层嵌套的序列展开成一个单层列表 |
| 9 | + |
| 10 | +| |
9 | 11 |
|
10 | 12 | ---------- |
11 | 13 | 解决方案 |
12 | 14 | ---------- |
13 | | -todo... |
| 15 | +可以写一个包含 ``yield from`` 语句的递归生成器来轻松解决这个问题。比如: |
| 16 | + |
| 17 | +.. code-block:: python |
| 18 | +
|
| 19 | + from collections import Iterable |
| 20 | +
|
| 21 | + def flatten(items, ignore_types=(str, bytes)): |
| 22 | + for x in items: |
| 23 | + if isinstance(x, Iterable) and not isinstance(x, ignore_types): |
| 24 | + yield from flatten(x) |
| 25 | + else: |
| 26 | + yield x |
| 27 | +
|
| 28 | + items = [1, 2, [3, 4, [5, 6], 7], 8] |
| 29 | + # Produces 1 2 3 4 5 6 7 8 |
| 30 | + for x in flatten(items): |
| 31 | + print(x) |
| 32 | +
|
| 33 | +在上面代码中, ``isinstance(x, Iterable)`` 检查某个元素是否是可迭代的。 |
| 34 | +如果是的话, ``yield from`` 就会返回所有子例程的值。最终返回结果就是一个没有嵌套的简单序列了。 |
| 35 | + |
| 36 | +额外的参数 ``ignore_types`` 和检测语句 ``isinstance(x, ignore_types)`` |
| 37 | +用来将字符串和字节排除在可迭代对象外,防止将它们再展开成单个的字符。 |
| 38 | +这样的话字符串数组就能最终返回我们所期望的结果了。比如: |
| 39 | + |
| 40 | +.. code-block:: python |
| 41 | +
|
| 42 | + >>> items = ['Dave', 'Paula', ['Thomas', 'Lewis']] |
| 43 | + >>> for x in flatten(items): |
| 44 | + ... print(x) |
| 45 | + ... |
| 46 | + Dave |
| 47 | + Paula |
| 48 | + Thomas |
| 49 | + Lewis |
| 50 | + >>> |
| 51 | +
|
| 52 | +| |
14 | 53 |
|
15 | 54 | ---------- |
16 | 55 | 讨论 |
17 | 56 | ---------- |
18 | | -todo... |
| 57 | +语句 `` yield from`` 在你想在生成器中调用其他生成器作为子例程的时候非常有用。 |
| 58 | +如果你不适用它的话,那么就必须写额外的for循环了。比如: |
| 59 | + |
| 60 | +.. code-block:: python |
| 61 | +
|
| 62 | + def flatten(items, ignore_types=(str, bytes)): |
| 63 | + for x in items: |
| 64 | + if isinstance(x, Iterable) and not isinstance(x, ignore_types): |
| 65 | + for i in flatten(x): |
| 66 | + yield i |
| 67 | + else: |
| 68 | + yield x |
| 69 | +
|
| 70 | +尽管只改了一点点,但是 ``yield from`` 语句看上去感觉更好,并且也使得代码更简洁清爽。 |
| 71 | + |
| 72 | +之前提到的对于字符串和字节的额外检查是为了防止将它们再展开成单个字符。 |
| 73 | +如果还有其他你不想展开的类型,修改参数ignore_types即可。 |
| 74 | + |
| 75 | +最后要注意的一点是,``yield from`` 在涉及到基于协程和生成器的并发编程中扮演着更加重要的角色。 |
| 76 | +可以参考12.12小节查看另外一个例子。 |
| 77 | + |
0 commit comments