python3: 迭代器与生成器(1)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python3: 迭代器与生成器(1),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1946字,纯文字阅读大概需要3分钟。
内容图文
![python3: 迭代器与生成器(1)](/upload/InfoBanner/zyjiaocheng/843/04bab5c9b8ba495eb1057a033adc0f7e.jpg)
1. 手动遍历迭代器
你想遍历一个可迭代对象中的所有元素,但是却不想使用for循环。
>>> items = [1, 2, 3] >>> # Get the iterator >>> it = iter(items) # Invokes items.__iter__() >>> # Run the iterator >>> next(it) # Invokes it.__next__() 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
2. 代理迭代
3.使用生成器创建新的迭代模式
一个函数中需要有一个 yield
语句即可将其转换为一个生成器。 跟普通函数不同的是,生成器只能用于迭代操作
>>> def countdown(n): ... print('Starting to count from', n) ... while n > 0: ... yield n ... n -= 1 ... print('Done!') ... >>> # Create the generator, notice no output appears >>> c = countdown(3) >>> c <generator object countdown at 0x1006a0af0> >>> # Run to first yield and emit a value >>> next(c) Starting to count from 3 3 >>> # Run to the next yield >>> next(c) 2 >>> # Run to next yield >>> next(c) 1 >>> # Run to next yield (iteration stops) >>> next(c) Done! Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
4. 实现迭代器协议
5. 反向迭代
6.带有外部状态的生成器函数
7.迭代器切片
函数 itertools.islice()
正好适用于在迭代器和生成器上做切片操作。比如:
>>> def count(n): ... while True: ... yield n ... n += 1 ... >>> c = count(0) >>> c[10:20] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'generator' object is not subscriptable >>> # Now using islice() >>> import itertools >>> for x in itertools.islice(c, 10, 20): ... print(x) ... 10 11 12 13 14 15 16 17 18 19
8. 跳过可迭代对象的开始部分
场景:你想遍历一个可迭代对象,但是它开始的某些元素你并不感兴趣,想跳过它们。
>>> from itertools import dropwhile >>> with open('/etc/passwd') as f: ... for line in dropwhile(lambda line: line.startswith('#'), f): ... print(line, end='') ...
如果你已经明确知道了要跳过的元素的个数的话,那么可以使用 itertools.islice()
来代替。
内容总结
以上是互联网集市为您收集整理的python3: 迭代器与生成器(1)全部内容,希望文章能够帮你解决python3: 迭代器与生成器(1)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。