Python3中zip,函数知识点小结

1.引言

在本文中,我将带领大家深入了解Python中的zip()函数,使用它可以提升大家的工作效率。

闲话少说,我们直接开始吧!

2. 基础知识

首先,我们来介绍一些基础知识点:

Python中的某些数据类型是不可变的(例如字符串、整数),而有些数据类型是可变的(如列表和字典)。不可变的数据对象在创建后不能更改,可变对象可以更改。

可迭代对象是一个单独返回其每个成员元素的对象。比如列表、元组、字符串和字典都是可迭代的对象。我们可以使用iter()或for循环来迭代可迭代对象。

当一个对象返回迭代器时,我们必须使用它来检索一个我们可以看到或使用的对象。

3. 向zip函数传递参数

我们可以在函数zip()中传递任意数量的可迭代项:

3.1 传递零个参数

样例如下:

>>> zipped = zip()
>>> list(zipped)
[]

上述代码中,我们向函数zip()传递了零个元素,此时该函数返回空。

3.2 传递一个参数

传递一个参数会创建一个元组集合,每个元组中都有一个元素。

示例代码如下:

# create a list of student names
>>> student_names = ['Lindsay', 'Harry', 'Peter']
# zip the list 
>>> zipped  = zip(student_names)
# consume with list()
>>> list(zipped)
[('Lindsay',), ('Harry',), ('Peter',)]

在上述代码中,我们创建了一个列表,其中有三个字符串表示三个学生的姓名。

3.3 传递两个参数

传递两个参数将创建一个具有成对的元组集合,其中第一个元素来自第一个参数,第二个元素来自第二个参数。

示例代码如下:

# create a list of student ids 
>>> student_ids = ['123', '4450', '5600']
# create a list of student names again, so that we do not forget the earlier steps!
>>> student_names = ['Lindsay', 'Harry', 'Peter']
# zip the lists 
>>> zipped  = zip(student_names, student_ids)
>>> list(zipped)
[('Lindsay', '123'), ('Harry', '4450'), ('Peter', '5600')]

在上述代码中,我们创建了另一个包含三个字符串的列表。此时,每个元素用于表示每个学生student_names的对应student_ids。

此时,我们可以使用for循环来遍历访问,样例代码如下:

>>> student_names = ['Lindsay', 'Harry', 'Peter']
>>> student_ids = ['123', '4450', '5600']
>>> for student_name, student_id in zip(student_names, student_ids): 
...     print(student_name, student_id)
... 
Lindsay 123
Harry 4450
Peter 5600

3.4 传递长度不等的参数

到目前为止,我们只研究了每个可迭代项长度相同的示例:包含学生姓名和id的列表长度都是3,但我们也可以传递不同长度的可迭代项。此时,zip函数将返回一个元组集合,其中元组的数量等于长度最小的可迭代项。它将忽略长度较长的可迭代项中的其余元素,如下所示:

# student_ids is a list with 4 elements 
>>> student_ids = ['123', '4450', '5600', '1']
# student_namdes is a list with 3 elements 
>>> student_names = ['Lindsay', 'Harry', 'Peter']
# zip is completely ignoring the last element of student_ids 
>>> list(zip(student_names, student_ids))
[('Lindsay', '123'), ('Harry', '4450'), ('Peter', '5600')]

>>> for student_name, student_id in zip(student_names, student_ids): 
...     print(student_name, student_id)
... 
Lindsay 123
Harry 4450
Peter 5600

从上面的示例中可以看到,函数zip对student_ids中的最后一个元素1没有做任何操作。因此,在传递给zip()之前,检查可迭代项的长度非常重要。

4. 总结

本文重点介绍了Python中关于zip函数的基础知识点总结,并给出了相应的代码示例。

原文地址:https://blog.csdn.net/sgzqc/article/details/129229033