[Python] Introduction to the built-in function zip class (function) and detailed use cases

Introduction to zip class (function)

The zip() function in Python is used to pack the elements of multiple iterable objects (such as lists, tuples, etc.) into tuples, and then return a list of these tuples. If the lengths of the individual iterable objects are inconsistent, the returned list is the same length as the shortest object.

Parameter Description:

*iterables: Indicates variable parameters, multiple iterable objects can be passed in.

strict: If True, check whether all input *iterables have the same length. If they are inconsistent, a ValueError will be thrown.

The essence of the zip class is an iterator.

Use Cases

*iterables have the same length, strict is 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 have different lengths, strict is 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 have different lengths, strict is 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]]

 

Guess you like

Origin blog.csdn.net/u011775793/article/details/135435414
Recommended