Python 3.x zip() 函数详解:用法、特性与实战场景
本文详解Python 3中zip()函数的核心机制与常见应用场景。重点解析zip返回的迭代器特性及其与Python 2返回列表的区别,介绍如何利用zip构建字典、对多序列进行排序及计算,并演示使用*操作符解压zip对象的技巧。
1. zip() 函数简介
在 Python 3.x 版本中,调用 zip() 函数会返回一个 zip 对象,该对象属于可迭代类型。
class zip(object):
"""
zip(*iterables) --> 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.
"""基于上述说明,可以总结出该迭代器的两个核心特征:
1. 调用迭代器的 next() 方法时,返回的是一个元组;该元组的第 i 个元素分别取自各个输入参数序列的第 i 个元素。
2. 当输入序列中最短的那个序列迭代完毕后,迭代器的 next() 方法将停止运行并抛出 StopIteration 异常。
为了直观展示 zip() 的效果,我们先观察一个最简单的示例。
def fun0():
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
result = zip(a, b)
print(type(result))
try:
while True:
print(next(result))
except StopIteration:
pass运行上述代码后,输出结果如下所示:
<class 'zip'> ('a', '1') ('b', '2') ('c', '3') ('d', '4')
从输出结果可以看出,zip() 函数返回的是一个 zip 对象。
由于 zip 对象是一个迭代器,我们可以通过 next() 方法对其进行遍历操作。
当然,也可以使用 for 循环来遍历 zip 对象中的元素。
def fun00():
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
result = zip(a, b)
for ele in result:
print(ele)('a', '1') ('b', '2') ('c', '3') ('d', '4')
2. 参数长度不等时的截断行为
当传入 zip() 函数的参数长度不一致时,zip() 会进行截断处理。具体而言,它会以最短的序列长度为准,超出该长度的其他序列元素将被丢弃。
def fun0():
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4', '5', '6']
result = zip(a, b)
try:
while True:
print(next(result))
except StopIteration:
pass运行上述方法后,得到的结果为:
('a', '1') ('b', '2') ('c', '3') ('d', '4')
3. Python 3.x 与 2.x 中 zip() 的区别
在 Python 3.x 中,zip() 返回的是一个 zip 对象,其本质是一个迭代器。而在 Python 2.x 中,zip() 直接返回一个 list 列表。
返回迭代器的主要优势在于节省内存占用,它仅在需要访问数据时才进行调用,实现了惰性求值。
4. 利用 zip() 构建字典
zip() 在实际开发中应用广泛,以下列举几个常用的实际案例。
zip() 可用于构建字典。
字典由键(key)和值(value)两部分组成。如果已存在 key 序列和 value 序列,使用 zip() 可以快速构建字典。
def fun5():
names = ['lili', 'lucy', 'tracy', 'larry']
scores = [98, 10, 75, 90]
my_dict = dict(zip(names, scores))
print(my_dict){'lili': 98, 'lucy': 10, 'tracy': 75, 'larry': 90}
5. 对多个序列元素进行排序
排序是日常开发中的常见需求,在不破坏元素相对关系的前提下对多个序列进行排序也非常普遍。下面通过一个典型案例进行说明。
沿用之前的数据示例。
现有 names 序列与 scores 序列,希望按照 names 进行排序,同时保持对应的 scores 数据关联。
def fun3():
names = ['lili', 'lucy', 'tracy', 'larry']
scores = [98, 10, 75, 90]
data = sorted(list(zip(names, scores)), key=lambda x: x[0], reverse=False)
print(data)输出结果为:
[('larry', 90), ('lili', 98), ('lucy', 10), ('tracy', 75)]
若希望按分数逆序排列,可运行如下代码:
def fun3():
names = ['lili', 'lucy', 'tracy', 'larry']
scores = [98, 10, 75, 90]
data = sorted(list(zip(names, scores)), key=lambda x: x[1], reverse=True)
print(data)[('lili', 98), ('larry', 90), ('tracy', 75), ('lucy', 10)]
6. 对多组数据进行计算
假设存在三个序列:sales(销售额)、costs(成本)和 allowances(补贴)。已知利润计算公式为:利润 = 销售额 - 成本 + 补贴。若要计算每组的利润,可以使用 zip() 方法。
def fun4():
sales = [10000, 9500, 9000]
costs = [9000, 8000, 7000]
allowances = [200, 100, 150]
for sale, cost, allowance in zip(sales, costs, allowances):
profit = sale - cost + allowance
print(f"profit is: {profit}")profit is: 1200 profit is: 1600 profit is: 2150
当然,也可以使用传统的 for 循环来实现。
def fun4():
sales = [10000, 9500, 9000]
costs = [9000, 8000, 7000]
allowances = [200, 100, 150]
for sale, cost, allowance in zip(sales, costs, allowances):
profit = sale - cost + allowance
print(f"profit is: {profit}") for i in range(len(sales)):
profit = sales[i] - costs[i] + allowances[i]
print(f"profit is: {profit}")相比之下,zip() 方法在代码表达上更为直观、简洁且优雅。
7. 使用 * 操作符进行解压
还可以利用 * 操作符对 zip 对象进行解压,其作用是将 zip object 还原为原始的序列对象,效果类似于解压压缩包。
def fun():
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
result = list(zip(a, b))
print(result)
zipobj = zip(a, b)
a1, a2 = zip(*zipobj)
print(list(a1))
print(a2)上述代码的运行结果为:
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')] ['a', 'b', 'c', 'd'] ('1', '2', '3', '4')
至此,关于 Python 3.x zip() 用法的详细介绍已完毕。如需了解更多 Python 3 中 zip 的相关内容,请搜索本站历史文章或继续浏览后续文章。感谢大家的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









