What's the Difference Between Iterators and Generators in Python

https://www.quora.com/Whats-the-difference-between-iterators-and-generators-in-Python

转载于:https://www.cnblogs.com/zhuangzebo/p/7613764.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! Here's an implementation of the `merge` generator function: ```python def merge(a, b): ia, ib = iter(a), iter(b) va, vb = next(ia), next(ib) while True: if va < vb: yield va va = next(ia) elif vb < va: yield vb vb = next(ib) else: yield va va, vb = next(ia), next(ib) ``` This generator function takes two infinite generators `a` and `b` that are in increasing order without duplicates, and returns a generator that has all the elements of both generators, also in increasing order without duplicates. The function first initializes two iterators `ia` and `ib` for the generators `a` and `b`, respectively. It then initializes the variables `va` and `vb` with the first elements of `a` and `b`, respectively. The function then enters an infinite loop that repeatedly compares the values of `va` and `vb` and yields the smaller value. If `va` is smaller than `vb`, the function yields `va` and advances the `ia` iterator to the next element of `a`. If `vb` is smaller than `va`, the function yields `vb` and advances the `ib` iterator to the next element of `b`. If `va` and `vb` are equal, the function yields `va` (since we want to remove duplicates) and advances both the `ia` and `ib` iterators to the next elements of `a` and `b`, respectively. Here's an example usage of this generator function: ```python >>> def gen1(): ... i = 0 ... while True: ... yield i ... i += 2 ... >>> def gen2(): ... i = 1 ... while True: ... yield i ... i += 2 ... >>> merged = merge(gen1(), gen2()) >>> [next(merged) for _ in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` This example defines two infinite generators `gen1` and `gen2` that generate all even and odd numbers, respectively. The `merge` function is then used to merge these two generators into a single generator `merged` that generates all the numbers in increasing order, without duplicates. Finally, the list comprehension `[next(merged) for _ in range(10)]` is used to consume the first 10 elements of `merged` and return them as a list. The result is `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`, which shows that `merged` generates all the even and odd numbers up to 9 in increasing order without duplicates.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值