跟老齐学Python之for循环语句

2019-10-05 17:04:00王振洲

zip

zip是什么东西?在交互模式下用help(zip),得到官方文档是:

zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.
通过实验来理解上面的文档:


>>> a = "qiwsir"
>>> b = "github"
>>> zip(a,b)
[('q', 'g'), ('i', 'i'), ('w', 't'), ('s', 'h'), ('i', 'u'), ('r', 'b')]
>>> c = [1,2,3]
>>> d = [9,8,7,6]
>>> zip(c,d)
[(1, 9), (2, 8), (3, 7)]
>>> e = (1,2,3)
>>> f = (9,8)
>>> zip(e,f)
[(1, 9), (2, 8)]

>>> m = {"name","lang"} 
>>> n = {"qiwsir","python"}
>>> zip(m,n)
[('lang', 'python'), ('name', 'qiwsir')]
>>> s = {"name":"qiwsir"}
>>> t = {"lang":"python"}
>>> zip(s,t)
[('name', 'lang')]

zip是一个内置函数,它的参数必须是某种序列数据类型,如果是字典,那么键视为序列。然后将序列对应的元素依次组成元组,做为一个list的元素。

下面是比较特殊的情况,参数是一个序列数据的时候,生成的结果样子:


>>> a 
'qiwsir'
>>> c 
[1, 2, 3]
>>> zip(c)
[(1,), (2,), (3,)]
>>> zip(a)
[('q',), ('i',), ('w',), ('s',), ('i',), ('r',)]

这个函数和for连用,就是实现了:


>>> c
[1, 2, 3]
>>> d
[9, 8, 7, 6]
>>> for x,y in zip(c,d):    #实现一对一对地打印
...     print x,y
...
1 9
2 8
3 7
>>> for x,y in zip(c,d):    #把两个list中的对应量上下相加。
...     print x+y
...
10
10
10

上面这个相加的功能,如果不用zip,还可以这么写:


>>> length = len(c) if len(c)<len(d) else len(d)    #判断c,d的长度,将短的长度拿出来
>>> for i in range(length):
...     print c[i]+d[i]
...
10
10
10

以上两种写法那个更好呢?前者?后者?哈哈。我看差不多了。还可以这么做呢:


>>> [ x+y for x,y in zip(c,d) ]
[10, 10, 10]

前面多次说了,list解析强悍呀。当然,还可以这样的:


>>> [ c[i]+d[i] for i in range(length) ]
[10, 10, 10]

for循环语句在后面还会经常用到,其实前面已经用了很多了。所以,看官应该不感到太陌生。