zip类(函数)介绍
Python中的zip()函数用于将多个可迭代对象(如列表、元组等)的元素打包成一个个元组,然后返回这些元组组成的列表。如果各个可迭代对象的长度不一致,则返回列表长度与最短的对象相同。
参数说明:
*iterables:表示可变参数,可以传入多个可迭代对象。
strict: 如果为True,则检查输入的所有 *iterables 是否长度一致,如果不一致,将会抛出ValueError。
zip类的本质是一个迭代器。
使用案例
*iterables的长度一样,strict为False
import types
def is_generator(obj):
"""
判断obj是否为生成器
"""
return isinstance(obj, types.GeneratorType)
def is_iterable(obj):
"""
判断obj是否为可迭代对象
"""
return hasattr(obj, '__iter__') and callable(obj.__iter__)
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [4.0, 5.0, 6.0]
# 将三个列表打包成一个元组列表
result = zip(list1, list2, list3)
print(result) # 输出:zip对象,其实是一个迭代成器
print('is_generator:', is_generator(result))
print('is_iterable:', is_iterable(result))
# 将元组解压为列表
unpacked_result = [list(item) for item in result]
print(unpacked_result) # 输出:[[1, 'a', 4.0], [2, 'b', 5.0], [3, 'c', 6.0]]
# 迭代器只能遍历一次,再次遍历,将会无效
unpacked_result = [list(item) for item in result]
print(unpacked_result)
*iterables的长度不一样,strict为False
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd', 'e']
list3 = [4.0, 5.0, 6.0]
# 将三个列表打包成一个元组列表
result = zip(list1, list2, list3, strict=False)
# 将元组解压为列表
unpacked_result = [list(item) for item in result]
print(unpacked_result) # 输出:[[1, 'a', 4.0], [2, 'b', 5.0], [3, 'c', 6.0]]
*iterables的长度不一样,strict为True
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd', 'e']
list3 = [4.0, 5.0, 6.0]
# 将三个列表打包成一个元组列表
result = zip(list1, list2, list3, strict=True)
# 将元组解压为列表
unpacked_result = [list(item) for item in result]
print(unpacked_result) # 输出:[[1, 'a', 4.0], [2, 'b', 5.0], [3, 'c', 6.0]]