【Python 3.6.1】迭代器
首先要创建迭代器,迭代器支持两种方法iter()和next()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# 定义列表 >>> L = ['zhangsan','lisi','wangwu','zhaoliu'] # 创建迭代器对象 >>> I = iter(L) # 输出下一个元素,从第一个元素开始 >>> next(I) 'zhangsan' >>> next(I) 'lisi' >>> next(I) 'wangwu' >>> next(I) 'zhaoliu' >>> next(I) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> |
for循环遍历迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
[root@dt xxf]# cat iter.py #!/usr/bin/python3 L = ['zhangsan','lisi','wangwu','zhaoliu'] ter = iter(L) for i in ter: print(i) [root@dt xxf]# # 执行python脚本 [root@dt xxf]# python iter.py zhangsan lisi wangwu zhaoliu [root@dt xxf]# |