Iterator and Generator
admin
2023-07-20 16:42:21
0
# Iterator  一个对象,代表了遗传数据流,使用__next__()方法或内置函数next()
# 返回连续的对象,没有数据返回时,抛出StopIteration异常

# iterable  一个对象,能每次返回数据组中的一个成员  for 循环中每次返回一个值 或
# 内置函数iter()传入参数返回iterator对象

# generator  使用了yield或者生成器表达式,申城iterator对象  用一种方便的
# 方法实现了iterator,在for循环取数据或使用next()取数据
# Iterator和Generator的关系
# 针对函数的列表进行优化
# 针对读取大文件进行优化
def gen_num():
    yield 8
    yield 99
    yield 999
g = gen_num()
g
next(g) # 第一次运行
---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

 in ()
----> 1 next(g) # 第一次运行

StopIteration: 
def gen_num2():
    for i in range(8):
        yield  i  # yield有类似返回值return的效果
for g in gen_num2():
    print(g)  # 每次取一个值的时候,才生成这个值,节省内存
0
1
2
3
4
5
6
7
my_list = [1,2,3]
next(my_list)  # 用 next方法验证是否为迭代器
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in ()
----> 1 next(my_list)

TypeError: 'list' object is not an iterator
next(iter(my_list))
1
next(iter(my_list))
1
it = iter(my_list)
next(it)
1
next(it)
2
from collections import Iterator, Iterable
isinstance(my_list, Iterator)
False
isinstance(iter(my_list), Iterator)
True
isinstance((), Iterator)
False
isinstance((), Iterable)  # 元组不是迭代器,但是可迭代
True
isinstance(range(8), Iterable)
True
isinstance(range(8), Iterator)
False

针对函数的列表进行优化

# Python 3:Fibonacci series up to n 
def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end='')
        a, b = b, a+b
        print()

fib(9)
0
1
1
2
3
5
8
def fil_list(n):
    a, b = 0, 1
    result = []
    while a < n:
        result.append(a) 
        a, b = b, a+b
    return result
fil_list(55)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fil_list(1000)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
def fib_gen(n):
    a, b = 0, 1
    while a< n:
        yield a
        a, b = b, a+b

fib_gen(80)
for i in fib_gen(80):
    print(i)
0
1
1
2
3
5
8
13
21
34
55
[i for i in fib_gen(66)]  # 列表推导式
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

针对读取大文件进行优化

import os
base_dir = r'D:\全栈\全栈资料\第三阶段 python进阶\文件与日志-演示代码\02-auto\data'
log_path = os.path.join(base_dir, 'access.log')
log_file = open(log_path)
log_data = log_file.readlines()
log_file.close()
len(log_data)
864
def read_log(log_path):
    with open(log_path) as f:
        print('Iterator:', isinstance(f, Iterator))  # open方法已经为我们生成一个迭代器
        for line in f:
            print(line)
            break

read_log(log_path)
Iterator: True
220.181.7.76 - - [20/May/2010:07:26:23 +0100] "GET / HTTP/1.1" 200 29460 "-" "Baiduspider+(+http://www.baidu.com/search/spider.htm)"

列表推导式

[i for i in fib_gen(6)]
[0, 1, 1, 2, 3, 5]
m = [i for i in fib_gen(6)]
for i in m:
    print(i)
0
1
1
2
3
5

生成器表达式

(i for i in fib_gen(5))
 at 0x0000014F3EAC9C50>
n = (i for i in fib_gen(9))
for i in n:
    print(i)
0
1
1
2
3
5
8

相关内容

热门资讯

原创 中... 尹希这个名字,或许并不是每个人都熟悉,但在科学圈内,他曾经是被反复提起的“少年天才”的典型代表。早在...
伊美谈判相关斡旋方21日在埃及... 新华社德黑兰6月19日电(记者陈霄 沙达提)据伊朗伊斯兰共和国广播电视台19日报道,埃及和巴基斯坦当...
减少国家干预,古巴通过170余... 据凤凰卫视报道,古巴总理马雷罗6月18日在会上公布了170多项举措,并获得一致通过。这些举措旨在减少...
郑州一汽车用品商城起火,有楼栋... 极目新闻记者 李贤诚6月19日晚,郑州市金水区居民陈先生反映,离他家百余米处的宏达国际车业广场突发火...
伊朗外长:美应对任何违反谅解备... 当地时间6月19日,伊朗外长阿拉格齐与巴基斯坦副总理兼外长达尔通电话。双方就地区局势交换了意见。通话...
科技创新如何改变普通人的生活 科技创新, 听起来好似实验室里那种高深莫测的课题, 事实上呢, 它已然静悄悄地走入了你我的平常生活里...
校长喊你吃饺子!大学最香最暖的... 又是一年毕业季,离别依依,情意浓浓。在这离别时刻,大连东软信息学院校长郭权走进食堂,挽起袖子,与毕业...
全球可用模型第一!智谱上线并开... 国产大模型慢慢追上来了! 6月17日,智谱上线并开源新一代旗舰大模型GLM-5.2,主攻“长程任务...
全球智能手机销量连续第九周同比... 【CNMO科技消息】市场研究机构Counterpoint Research最新发布的周度销量追踪数据...
2026年抱箍太阳能路灯区域深... 抱箍太阳能路灯是一种无需预埋基础、通过抱箍结构直接固定在现有灯杆上的太阳能照明产品,其安装灵活、适配...