yield列表反转 islice切片
列表反转
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
原文地址:https://www.cnblogs.com/wangjiale1024/p/10349351.html
时间: 2024-11-06 15:38:53