# yield列表反转 islice切片
### 列表反转
```python
l1 = [i for i in range(10)]
print(l1)
print(l1[::2])
l1.reverse()
# 注: python2里列表reverse是返回一个新的列表
print(l1)
print(l1[::-1])
for x in reversed(l1):
print(x)
```
output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
2
3
4
5
6
7
8
9

实际上,for循环要求l1有这个函数, __iter__ 反向循环reveresd要求l1有__reveresd__

l1.__iter__()
l1.__reversed__()

自己实现一个可以反转的列表

class FloatRange:
def __init__(self, start, end, step):
self.start = start
self.end = end
self.step = step def __iter__(self):
res = self.start
while res <= self.end:
yield res
res += self.step def __reversed__(self):
res = self.end
while res >= self.start:
yield res
res -= self.step for i in FloatRange(1, 10, 0.5):
print(i)
print('#============')
for i in reversed(FloatRange(1, 10, 0.5)):
print(i)

本文和前文有很多yiled的例子,也讲了读文件的分片,介绍一个可以分片的函数 itertools.islice

islice(iter, start=0, end, step=1)

# 运行这个代码可以看到with 0和1输出相同
# f 0 1输出不同,是因为islice会消耗iter
from itertools import islice
print("#======with 0======\n\n")
with open('2.5生成器.md', 'r') as f:
for i in islice(f, 100, 110):
print(i)
print("#======with 1======\n\n")
with open('2.5生成器.md', 'r') as f:
for i in islice(f, 100, 110):
print(i) print("#======f 0======\n\n")
# 对同一个f进行操作
f = open('2.5生成器.md', 'r')
for i in islice(f, 0, 10):
print(i)
print("#======f 1======\n\n")
for i in islice(f, 0, 10):
print(i)

简单的例子展示islice消耗iter

l = range(10)
l = iter(l)
for i in islice(l, 0, 5, 2):
print(i) print('一直输出到结束')
for i in islice(l, 0, None):
print(i)

output:

0
2
4
一直输出到结束
5
6
7
8
9

最新文章

  1. Web API项目中使用Area对业务进行分类管理
  2. pypi上传库
  3. jquery datepicker 只显示年月
  4. How to save milliseconds to DB in NHibernate
  5. BZOJ3735 : [Pa2013]Konduktorzy
  6. JBPM表达业务流程(流程定义语言)
  7. 利用Hadoop实现超大矩阵相乘之我见(一)
  8. PowerMock简介
  9. Maven介绍,包括作用、核心概念、用法、常用命令、扩展及配置
  10. Apache中RewriteCond规则参数介绍(转)
  11. django中数据库操作——in操作符
  12. Docker下安装rabbitmq
  13. Spring 4 : 整合 SSH
  14. linux环境下mongodb启动操作
  15. poco
  16. selenium-java web自动化测试工具抓取百度搜索结果实例
  17. [UE4]条件语句Select
  18. chain33 区块链开发框架诞生记
  19. Backbone.js 的 View 中定义事件
  20. Java实战_手把手编写记事本

热门文章

  1. python find()函数
  2. 框架-.NET:.NET Core
  3. Tomcat负载均衡、调优核心应用进阶学习笔记(三):LNMT nginx+tomcat、LAMT apache+tomcat、session会话保持、不错的站点
  4. 运维 04 Shell基础命令(二)
  5. yum常见问题
  6. Eureka 系列(04)客户端源码分析
  7. 挂载时出现mount: RPC: Unable to receive; errno = Connection refused错误的解决方法
  8. Oracle多种表连接方式
  9. Python之字符串搜索和替换
  10. 一、hibernate环境搭建