# Python：zip的妙用

387人阅读 评论(0)

 1 >>> name=('jack','beginman','sony','pcky')
2 >>> age=(2001,2003,2005,2000)
3 >>> for a,n in zip(name,age):
4     print a,n
5
6 输出：
7 jack 2001
8 beginman 2003
9 sony 2005
10 pcky 2000

1 all={"jack":2001,"beginman":2003,"sony":2005,"pcky":2000}
2 for i in all.keys():
3     print i,all[i]
4
5 输出：
6 sony 2005
7 pcky 2000
8 jack 2001
9 beginman 2003

1 >>> type(sorted(s))
2 <type 'list'>
3 >>> type(zip(s))
4 <type 'list'>
5 >>> type(reversed(s))
6 <type 'listreverseiterator'>
7 >>> type(enumerate(s))
8 <type 'enumerate'>

1 >>> help(zip)
2 Help on built-in function zip in module __builtin__:
3
4 zip(...)
5     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
6
7     Return a list of tuples, where each tuple contains the i-th element
8     from each of the argument sequences.  The returned list is truncated
9     in length to the length of the shortest argument sequence.

 1 >>> z1=[1,2,3]
2 >>> z2=[4,5,6]
3 >>> result=zip(z1,z2)
4 >>> result
5 [(1, 4), (2, 5), (3, 6)]
6 >>> z3=[4,5,6,7]
7 >>> result=zip(z1,z3)
8 >>> result
9 [(1, 4), (2, 5), (3, 6)]
10 >>> 

zip()配合*号操作符,可以将已经zip过的列表对象解压

1 >>> zip(*result)
2 [(1, 2, 3), (4, 5, 6)]

* 二维矩阵变换（矩阵的行列互换）

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print [ [row[col] for row in a] for col in range(len(a[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

zip函数接受任意多个序列作为参数，将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列，新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能，即将合并的序列拆成多个tuple。
①tuple的新序列
>>>>x=[1,2,3],y=['a','b','c']
>>>zip(x,y)
[(1,'a'),(2,'b'),(3,'c')]

②新的序列的长度以参数中最短的序列为准.
>>>>x=[1,2],y=['a','b','c']
>>>zip(x,y)
[(1,'a'),(2,'b')]

③(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple。
>>>>x=[1,2,3],y=['a','b','c']
>>>>zip(*zip(x,y))
[(1,2,3),('a','b','c')]

其他高级应用：

1.zip打包解包列表和倍数
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]

2. 使用zip合并相邻的列表项

>>> a = [1, 2, 3, 4, 5, 6]
>>> zip(*([iter(a)] * 2))
[(1, 2), (3, 4), (5, 6)]

>>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))
[(1, 2, 3), (4, 5, 6)]
[(1, 2), (3, 4), (5, 6)]
[(1,), (2,), (3,), (4,), (5,), (6,)]

>>> zip(a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]

>>> zip(a[::3], a[1::3], a[2::3])
[(1, 2, 3), (4, 5, 6)]

>>> group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
[(1, 2, 3), (4, 5, 6)]
[(1, 2), (3, 4), (5, 6)]
[(1,), (2,), (3,), (4,), (5,), (6,)]

3.使用zip和iterators生成滑动窗口 (n -grams)
>>> from itertools import islice
>>> def n_grams(a, n):
...     z = (islice(a, i, None) for i in range(n))
...     return zip(*z)
...
>>> a = [1, 2, 3, 4, 5, 6]
>>> n_grams(a, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> n_grams(a, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> n_grams(a, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]

4.使用zip反转字典
>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> m.items()
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
>>> zip(m.values(), m.keys())
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
>>> mi = dict(zip(m.values(), m.keys()))
>>> mi
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：44824次
• 积分：418
• 等级：
• 排名：千里之外
• 原创：14篇
• 转载：7篇
• 译文：1篇
• 评论：6条
文章分类
阅读排行
最新评论