• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

jwang106


脚踏实地,日拱一卒。 建立新的神经链接,可不像公园散步那样简单。
  • 博客园
  • 联系
  • 管理

View Post

yield列表反转 islice切片(2.6)


# 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

posted on 2019-02-02 22:33  jwang106  阅读(184)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3