您好,欢迎来到年旅网。
搜索
您的当前位置:首页python 迭代器(iterator),迭代器协议,可迭代对象(iterable)

python 迭代器(iterator),迭代器协议,可迭代对象(iterable)

来源:年旅网

三个的含义

class Iter(object):
    def __init__(self, x):
        self.x = x

    def __iter__(self):
        return self
        # 只执行一次,返回一个迭代器对象

    def __next__(self):
        self.x += 1
        if self.x > 10:
            raise StopIteration
        return self.x
        # 多次执行,每次返回迭代的下一项


sample = Iter(1)
print(next(sample)) # 2
print(next(sample)) # 3
print(next(sample)) # 4
for i in sample:
    print(i, end=' ') # 5 6 7 8 9 10
for i in sample:
    print(i, end=' ') # 这里什么都没有

for循环

for循环的本质是先调用 iter() 函数将可迭代对象转化为一个迭代器对象,然后每次循环调用一次 next() 函数,得到迭代的下一项。

# 例如下
class Iter(object):
    def __init__(self, x):
        self.x = x

    def __iter__(self):
        return self
        # 必须返回迭代器对象

    def __next__(self):
        self.x += 1
        if self.x > 10:
            raise StopIteration
        return self.x
        # 返回迭代的下一项


sample = Iter(1)
for i in sample:
    print(i, end=' ')
print('')
sample_1 = Iter(1)
# for 循环的执行过程如下
iterable = iter(sample_1)
# 先利用 iter() 函数将可迭代对象转化为迭代器对象
n = 10
while n > 1:
    print(next(iterable), end=' ')
    # 然后不断的用 next() 函数调用迭代器对象,以返回下一个值
    n = n-1

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务