码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-20 18:52:09      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:ack   items   rac   基本   manual   ace   迭代   bsp   使用   

 

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循环

标签:ack   items   rac   基本   manual   ace   迭代   bsp   使用   

原文地址:https://www.cnblogs.com/sea-stream/p/10566633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!