yield列表反转 islice切片(2.6)
2024-09-03 03:14:46
# 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
最新文章
- Web API项目中使用Area对业务进行分类管理
- pypi上传库
- jquery datepicker 只显示年月
- How to save milliseconds to DB in NHibernate
- BZOJ3735 : [Pa2013]Konduktorzy
- JBPM表达业务流程(流程定义语言)
- 利用Hadoop实现超大矩阵相乘之我见(一)
- PowerMock简介
- Maven介绍,包括作用、核心概念、用法、常用命令、扩展及配置
- Apache中RewriteCond规则参数介绍(转)
- django中数据库操作——in操作符
- Docker下安装rabbitmq
- Spring 4 : 整合 SSH
- linux环境下mongodb启动操作
- poco
- selenium-java web自动化测试工具抓取百度搜索结果实例
- [UE4]条件语句Select
- chain33 区块链开发框架诞生记
- Backbone.js 的 View 中定义事件
- Java实战_手把手编写记事本
热门文章
- python find()函数
- 框架-.NET:.NET Core
- Tomcat负载均衡、调优核心应用进阶学习笔记(三):LNMT nginx+tomcat、LAMT apache+tomcat、session会话保持、不错的站点
- 运维 04 Shell基础命令(二)
- yum常见问题
- Eureka 系列(04)客户端源码分析
- 挂载时出现mount: RPC: Unable to receive; errno = Connection refused错误的解决方法
- Oracle多种表连接方式
- Python之字符串搜索和替换
- 一、hibernate环境搭建