极客编程python入门-迭代器
原创
©著作权归作者所有:来自51CTO博客作者最爱大苹果的原创作品,请联系作者获取转载授权,否则将追究法律责任
可以直接作用于for循环的对象统称为可迭代对象:Iterable。
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
list、dict、str虽然是Iterable,却不是Iterator
小结
1、凡是可作用于for循环的对象都是Iterable类型;
2、凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
3、集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

test_list = [1,2,3,4,5]
test_dirt = {
"name":"张三",
"sex":"男",
"age":33
}
test_tuple = (1,2,3,4,5)
test_set = {1,2,3,3,4}
for i in test_list:
print(i)
for i in test_dirt:
print(i)
for i in test_tuple:
print(i)
for i,j in test_set.items():
print("%s:%s" % (i,j))
# >>> 执行结果如下:
# >>> test_list的元素为: 1
# >>> test_list的元素为: 2
# >>> test_list的元素为: 3
# >>> test_list的元素为: 4
# >>> test_list的元素为: 5
# >>> test_dirt的元素为: name
# >>> test_dirt的元素为: sex
# >>> test_dirt的元素为: age
# >>> test_tuple的元素为: 1
# >>> test_tuple的元素为: 2
# >>> test_tuple的元素为: 3
# >>> test_tuple的元素为: 4
# >>> test_tuple的元素为: 5
# >>> test_set的元素为:1
# >>> test_set的元素为:2
# >>> test_set的元素为:3
# >>> test_set的元素为:4
def make_iter():
for i in range(5):
yield i
iter_obj = make_iter()
for i in iter_obj:
print(i)
print('----')
for i in iter_obj:
print(i)
# >>> 执行结果如下:
# >>> 0
# >>> 1
# >>> 2
# >>> 3
# >>> 4
# >>> ----
# >>> 从运行结果得出结论,当我们从内存中读取完迭代器所有的值后,内存就会被释放,不再循环输出。