python中可迭代对象
1.可迭代对象
... print(num) ... 11 22 33
list这种数据类型虽然有下标,但很多其他数据类型是没有下标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,比如dict就可以迭代:
>>> for key in d:
... print(key)
...
a
c
b
由于字符串也是可迭代对象,因此,也可以作用于for循环:
... print(str)
...
p
y
t
h
o
n
2. 如何判断一个对象是否可以迭代
In [51]: isinstance([], Iterable)
Out[51]: True
In [52]: isinstance({}, Iterable)
Out[52]: True
In [53]: isinstance('abc', Iterable)
Out[53]: True
In [54]: isinstance(mylist, Iterable)
Out[54]: False
In [55]: isinstance(100, Iterable)
Out[55]: False
3. 可迭代对象的本质
...   def __init__(self):
...     self.container = []
...   def add(self, item):
...     self.container.append(item)
...   def __iter__(self):
...     """返回一个迭代器"""
...     # 我们暂时忽略如何构造一个迭代器对象
...     pass
...
>>> mylist = MyList()
>>> from collections import Iterable
>>> isinstance(mylist, Iterable)
True
>>>
# 这回测试发现添加了__iter__方法的mylist对象已经是一个可迭代对象了
>>> li_iter = iter(li)
>>> next(li_iter)
11>>> next(li_iter)
22>>> next(li_iter)
33>>> next(li_iter)
44>>> next(li_iter)
55>>> next(li_iter)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
注意,当我们已经迭代完最后一个数据之后,再次调用next()函数会抛出StopIteration的异常,来告诉我们所有数据都已迭代完成,不用再执行next()函数了。
 
                    
                     
                    
                 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号