博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python中的内置函数zip函数

Posted on 2024-02-20 17:55  生活旅行家  阅读(28)  评论(0)    收藏  举报

关于zip()函数,有几点要讲的。

首先,官方文档中,它是这样描述的:

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

翻译:

创建一个从每个可迭代对象中聚合元素的迭代器。

返回元组的迭代器,其中第i个元组包含来自每个参数序列或可迭代对象的第i个元素。当最短的输入可迭代对象耗尽时,迭代器停止。如果有一个可迭代参数,它将返回一个一元组的迭代器。如果没有参数,则返回空迭代器。

常见的使用方法为:

字典的排序。

prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 202.55,
    'HPQ': 37.2,
    'FB': 10.75
}
prices_zip = zip(prices.values(), prices.keys())
min_price = min(prices_zip)

zip()返回的是一个tuple类型的迭代器。且只能调用一次。如果把它转换为list类型并存储,可以实现多次调用。

zip()实现的是将多个list合并为一个zip类型的序列,类似于压缩。

怎么实现解压缩呢?

origin = zip(*prices_zip)可以获得两个list序列,得到合并前的数据,即为解压缩。