当前位置: 首页 > 文档资料 > 跟老齐学 Python >

zip()补充

优质
小牛编辑
119浏览
2023-12-01

因为耶和华赐人智慧,知识和聪明都由他口而出。他给正直人存留真智慧,给行为纯正的人作盾牌,为要保守公平人的路,护庇虔敬人的道。你也必明白仁义、公平、正直,一切的善道。智慧必入你心,你的灵要以知识为美。谋略必护卫你,聪明必保守你,要救你脱离恶道(注:或作“恶人的道”),脱离说乖谬话的人。(箴言书 2:6-12)

zip()补充

《语句(4)》中,对zip()进行了阐述,但是,由于篇幅限制,没有阐述的太完整。所以,本讲再次将它拿出来,希望能够有一个完成的独立阐述,以便学习者参考。

内建函数zip()

zip()是一个内建函数,对它的描述为:

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

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.

zip()的参数是可迭代对象。例如:

>>> colors = ["red", "green", "blue"]>>> values = [234, 12, 89, 65]>>> for col, val in zip(colors, values):    ...     print (col, val)     #Python 3: print((col, val))    ...     ('red', 234)    ('green', 12)    ('blue', 89)

注意观察,zip()自动进行了匹配,并且抛弃不对应的项。

参数*iterables

这是zip()的雕虫小技。

文档中显示zip()的参数使*iterables,这是什么意思呢?

《函数(3)》 中,讲述“参数收集”和“另外一种传值”方法时,遇到过类似的参数,把其中一个例子再拿出来欣赏:

>>> def add(x,y):    ...     return x + y    ... >>> add(2,3)5>>> bars = (2,3)>>> add(*bars)5

zip()也类似上面示例中构造的那个add()函数。

>>> dots = [(1, 2), (3, 4), (5, 6)]>>> x, y = zip(*dots)>>> x(1, 3, 5)>>> y(2, 4, 6)

利用这个功能,就比较容易实现矩阵的转置了。补充:关于矩阵的知识,可以参阅维基百科词条:矩阵

>>> m = [[1, 2],          [3, 4],          [5, 6]]>>> zip(*m)       #Python 3: list(zip(*m))[(1, 3, 5),  (2, 4, 6)]

下面再看一个有点绚丽的:

>>> seq = range(1, 10)>>> zip(*[iter(seq)]*3)        #Python 3: list(zip(*[iter(seq)]*3))[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

感觉有点太炫酷了,不是太好理解。其实,分解一下,就是:

>>> x = iter(range(1, 10))>>> zip(x, x, x)        # Python 3: list(zip(x, x, x) )[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

这种炫酷的代码,我不提倡应用到编程实践中,这里仅仅是展示一下zip()的使用罢了。

关于在字典中使用zip()就不做过多介绍了,因为在 《语句(4)》 中已经做了完整阐述。

更酷的示例

最后,展示一个来自网络的示例,或许在某些时候用一下,能够人前炫耀。

>>> a = [1, 2, 3, 4, 5]>>> b = [2, 2, 9, 0, 9]>>> map(lambda pair: max(pair), zip(a, b))        #Python 3: list(map(lambda pair: max(pair), zip(a, b)))[2, 2, 9, 4, 9]

参考: