- 可迭代对象
str(字符串),list(列表),tuple(元组),set(集合),f(文件句柄),dict(字典)
f(文件句柄)并且是迭代器,其余只是可迭代对象
lst = [2,3,4,5]
print(dir(lst)) #dir() 获取对象列表
print()
print(dir(1))
# 可迭代
print('列表','__iter__' in dir([2,3,4,5])) #列表
print('元组','__iter__' in dir((2,3))) #元组
print('集合','__iter__' in dir({'a','b'})) #集合
print('字典','__iter__' in dir({'a':10,'b':20})) #字典
print('字符串','__iter__' in dir('2')) #字符串
print('数字','__iter__' in dir(1)) #数字
结果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
列表 True
元组 True
集合 True
字典 True
字符串 True
数字 False
- 模拟for循环,(for循环本质)
lst = ['a','b','c'] it = lst.__iter__() while 1: try: name = it.__next__() #获取当前,并且指针移到下一个元素 print(name) except StopIteration: break
结果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
a
b
c -
是否迭代器
-
1 方法一
lst = ['a','b','c'] print('__next__' in dir(lst))
结果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
False - 2 方法二
#注意3.7.1会警告 from collections import Iterable #可迭代对象 from collections import Iterator #迭代器 lst = ['a','b','c'] print(isinstance(lst,Iterable)) #isinstance(对象,类型)对象的实例 print(isinstance(lst,Iterator))
结果:原因from collections import Iterable这种写法在3.8将废除
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
F:/myPy/test.py:79: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
True
False
from collections import Iterable #可迭代的
F:/myPy/test.py:80: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
from collections import Iterator #迭代器 - 2_1 修正
from collections.abc import Iterable #可迭代对象 from collections.abc import Iterator #迭代器 lst = ['a','b','c'] print(isinstance(lst,Iterable)) #isinstance(对象,类型)对象的实例 print(isinstance(lst,Iterator))
结果:
F:\myPy\venv\Scripts\python.exe F:/myPy/test.py
True
False
-
- 总结:
# 迭代器包含:__next__,__iter__ # 可迭代对象只有:__iter__
迭代器:
- 节省内存
- 惰性机制
- 不能反复,只能向下执行(如for循环)