遍历一个可迭代对象中的所有元素,但是却不想使用for循环

Posted F

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了遍历一个可迭代对象中的所有元素,但是却不想使用for循环相关的知识,希望对你有一定的参考价值。

 

def manual_iter():
    with open(/etc/passwd) as f:
        try:
            while True:
                line = next(f)
                print(line, end=‘‘)
        except StopIteration:
            pass

or

with open(/etc/passwd) as f:
    while True:
        line = next(f, None)
        if line is None:
            break
        print(line, end=‘‘)

下面的交互示例向我们演示了迭代期间所发生的基本细节:

>>> items = [1, 2, 3]
>>> # Get the iterator
>>> it = iter(items) # Invokes items.__iter__()
>>> # Run the iterator
>>> next(it) # Invokes it.__next__()
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
StopIteration
>>>

 

 

以上是关于遍历一个可迭代对象中的所有元素,但是却不想使用for循环的主要内容,如果未能解决你的问题,请参考以下文章

Python迭代器与生成器

迭代器

设计模式之迭代器模式

设计模式之迭代器模式

迭代器生成器

可迭代对象迭代器生成器的区别