python3 zip()

本文介绍如何创建一个聚合迭代器,从多个迭代器中提取元素并组合成元组,详细解释了zip函数的工作原理及其等价实现,并通过实例展示了如何使用zip函数将迭代器聚合为元组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. Equivalent to:
def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterables = [iter(it) for it in iterables]
    while iterables:
        result = []
        for it in iterables:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)
举例:
>>> k = list(zip(*[[1,2,3],[4,5,6]]))
>>> k
[(1, 4), (2, 5), (3, 6)]

zip()是内置函数, 能把迭代对象进行聚合,返回值是迭代对象-聚合后的元组,用list()函数把它转化为列表

文档那个等价函数值得学习,那个iter()、next()用法并不简单。



>>> k = list(zip(*[[1,2,3],[4,5,6]]))
>>> k
[(1, 4), (2, 5), (3, 6)]
>>> k=zip(*[[1,2,3],[4,5,6]])
>>> k
<zip object at 0x000000000313F088>
>>> list(k)
[(1, 4), (2, 5), (3, 6)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值