|
| 1 | +#再论zip() |
| 2 | + |
| 3 | +在 [《语句(4)》](./124.md)中,对zip()进行了阐述,但是,由于篇幅限制,没有阐述的太完整。所以,本讲再次将它拿出来,希望能够有一个完成的独立阐述,以便学习者参考。 |
| 4 | + |
| 5 | +##内建函数zip() |
| 6 | + |
| 7 | +zip()是一个内建函数,对它的描述为: |
| 8 | + |
| 9 | +>zip(*iterables) |
| 10 | +
|
| 11 | +>Make an iterator that aggregates elements from each of the iterables. |
| 12 | +
|
| 13 | +>Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. |
| 14 | +
|
| 15 | +zip()的参数是可迭代对象。例如: |
| 16 | + |
| 17 | + >>> colors = ["red", "green", "blue"] |
| 18 | + >>> values = [234, 12, 89, 65] |
| 19 | + >>> for col, val in zip(colors, values): |
| 20 | + ... print (col, val) |
| 21 | + ... |
| 22 | + ('red', 234) |
| 23 | + ('green', 12) |
| 24 | + ('blue', 89) |
| 25 | + |
| 26 | +注意观察,zip()自动进行了匹配,并且抛弃不对应的项。 |
| 27 | + |
| 28 | +##参数*iterables |
| 29 | + |
| 30 | +这是zip()的雕虫小技了,在前面的文档中,zip()的参数使`*iterables`,这是什么意思呢? |
| 31 | + |
| 32 | +在 [《函数(3)》](./203.md) 中,讲述“参数收集”和“另外一种传值”方法时,遇到过类似的参数,把其中一个例子再拿出来欣赏: |
| 33 | + |
| 34 | + >>> def add(x,y): |
| 35 | + ... return x + y |
| 36 | + ... |
| 37 | + >>> add(2,3) |
| 38 | + 5 |
| 39 | + >>> bars = (2,3) |
| 40 | + >>> add(*bars) |
| 41 | + 5 |
| 42 | + |
| 43 | +zip()也类似上面示例中构造的那个add()函数。 |
| 44 | + |
| 45 | + >>> dots = [(1, 2), (3, 4), (5, 6)] |
| 46 | + >>> x, y = zip(*dots) |
| 47 | + >>> x |
| 48 | + (1, 3, 5) |
| 49 | + >>> y |
| 50 | + (2, 4, 6) |
| 51 | + |
| 52 | +利用这个功能,就比较容易实现矩阵的转置了。补充:关于矩阵的知识,可以参阅维基百科词条:[矩阵](https://zh.wikipedia.org/zh/%E7%9F%A9%E9%98%B5) |
| 53 | + |
| 54 | + >>> m = [[1, 2], |
| 55 | + [3, 4], |
| 56 | + [5, 6]] |
| 57 | + >>> zip(*m) |
| 58 | + [(1, 3, 5), |
| 59 | + (2, 4, 6)] |
| 60 | + |
| 61 | +下面再看一个有点绚丽的: |
| 62 | + |
| 63 | + >>> seq = range(1, 10) |
| 64 | + >>> zip(*[iter(seq)]*3) |
| 65 | + [(1, 2, 3), (4, 5, 6), (7, 8, 9)] |
| 66 | + |
| 67 | +感觉有点太炫酷了,不是太好理解。其实,分解一下,就是: |
| 68 | + |
| 69 | + >>> x = iter(range(1, 10)) |
| 70 | + >>> zip(x, x, x) |
| 71 | + [(1, 2, 3), (4, 5, 6), (7, 8, 9)] |
| 72 | + |
| 73 | +这种炫酷的代码,我不提倡应用到编程实践中,这里仅仅使展示一下zip()的使用罢了。 |
| 74 | + |
| 75 | +关于在字典中使用zip()就不做过多介绍了,因为在 [《语句(4)》](./124.md) 中已经做了完整阐述。 |
| 76 | + |
| 77 | +##更酷的示例 |
| 78 | + |
| 79 | +最后,展示一个来自网络的示例,或许在某些时候用一下,能够人前炫耀。 |
| 80 | + |
| 81 | + >>> a = [1, 2, 3, 4, 5] |
| 82 | + >>> b = [2, 2, 9, 0, 9] |
| 83 | + >>> map(lambda pair: max(pair), zip(a, b)) |
| 84 | + [2, 2, 9, 4, 9] |
| 85 | + |
0 commit comments