1. 概念
1.1 描述
zip() 函数用于将可迭代的对象
作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同
,利用 * 号操作符,可以将元组解压为列表。
注意:
Py3和Py2中,zip函数有所不同
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
1.2 语法
zip(iter1 [,iter2 [...]])
参数说明:
iter 一个或多个迭代器
源码内容:
class zip(object):
"""
zip(iter1 [,iter2 [...]]) --> zip object
Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, iter1, iter2=None, *some): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
1.3 返回值
- py2.X直接返回元组列表;
- py3.X返回元组列表的对象,需要手动执行list方法进行转换
2. 实例
zip函数支持压缩,同时也支持解压
lst01 = ['a','b','c']
lst02 = ['d','e','f']
lst03 = ['g','h','i','j']
# 1.压缩
# 1.1 元素个数相同
lst_new_obj01 = zip(lst01,lst02)
print(lst_new_obj01) # <zip object at 0x102d48848> py3中默认zip函数默认返回一个对象
# py3中,zip函数默认返回一个对象,如上,如果需要展示,需要通过手动通过list方法进行转换
lst_new01 = list(lst_new_obj01)
# 1.2 元素个数不同
lst_new_obj02 = zip(lst01,lst03)
lst_new02 = list(lst_new_obj02)
# 1.3 元素个数不同&多个可迭代对象
lst_new_obj03 = zip(lst01,lst02,lst03)
lst_new03 = list(lst_new_obj03)
print(lst_new01) # [('a', 'd'), ('b', 'e'), ('c', 'f')]
print(lst_new02) # [('a', 'g'), ('b', 'h'), ('c', 'i')]
print(lst_new03) # [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
# 2 解压
# 2.1 以下方法无法获取解压结果,获取的是空列表,此方法不可行
unzip03_01 = zip(*lst_new_obj03)
unzip03_02 = zip(*lst_new03)
print(unzip03_01) # <zip object at 0x10373bb08>
print(unzip03_02) # <zip object at 0x10373bb08>
unzip03_fin = list(unzip03_01)
print(unzip03_fin) # []
# 2.2 py3正确解压方式
print(zip(*zip(lst01,lst02,lst03))) # <zip object at 0x10363bc08>
print(list(zip(*zip(lst01,lst02,lst03)))) # [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i')]
# 注意:看上述,解压方法,其实看返回的解压后的内存地址是不同的,具体原因也不太清楚