Confused with python lists: are they or are they not iterators?

前端 未结 4 1697
深忆病人
深忆病人 2020-12-02 08:25

I am studying Alex Marteli\'s Python in a Nutshell and the book suggests that any object that has a next() method is (or at least can be used as) an ite

4条回答
  •  一向
    一向 (楼主)
    2020-12-02 09:08

    You need to convert list to an iterator first using iter():

    In [7]: x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    In [8]: it=iter(x)
    
    In [9]: for i in range(10):
        it.next()
       ....:     
       ....:     
    Out[10]: 0
    Out[10]: 1
    Out[10]: 2
    Out[10]: 3
    Out[10]: 4
    Out[10]: 5
    Out[10]: 6
    Out[10]: 7
    Out[10]: 8
    Out[10]: 9
    
    In [12]: 'next' in dir(it)
    Out[12]: True
    
    In [13]: 'next' in dir(x)
    Out[13]: False
    

    checking whether an object is iterator or not:

    In [17]: isinstance(x,collections.Iterator)
    Out[17]: False
    
    In [18]: isinstance(x,collections.Iterable)
    Out[18]: True
    
    In [19]: isinstance(it,collections.Iterable) 
    Out[19]: True
    
    In [20]: isinstance(it,collections.Iterator)
    Out[20]: True
    

提交回复
热议问题