zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
“Return a list of tuples, where each tuple contains the ith element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument”
其大致意思就是分别提取N个列表的第i个元素组成一个元组,然后再将这些元组作为基本元素构成一个列表,其中列表的长度与最短的列表一致。zip函数的输入对象除列表以外,还可以是元组,但其输出均是以元组为元素的列表
#!/usr/bin/python
# -*- coding: utf-8 -*-
x=(1,2,3)
y=(4,5,6)
z=(7,8,9)
a1=zip(x,y,z)
print("a1={} 针对多个列表使用zip".format(list(a1)))
a2=zip(x)
print("a2={} 一个列表使用zip".format(list(a2)))
X=["a","b"]
a3=zip(x,X)
print("a2={} zip对长度的处理".format(list(a3)))
a4=zip(*zip(x,y))
print("a4={} 解zip过程".format(list(a4)))
---------------------
a1=[(1, 4, 7), (2, 5, 8), (3, 6, 9)] 针对多个列表使用zip
a2=[(1,), (2,), (3,)] 一个列表使用zip
a3=[(1, 'a'), (2, 'b')] zip对长度的处理
a4=[(1, 2, 3), (4, 5, 6)] 解zip过程