本文讲述了以下几个方面:

  1.何为迭代,何为可迭代对象,何为生成器,何为迭代器?

  2.可迭代对象与迭代器之间的区别

  3.生成器内部原理解析,for循环迭代内部原理解析

  4.可迭代对象,迭代器,生成器,生成器函数之间关系

1.迭代  

  要搞清楚什么关于迭代器,生成器,可迭代对象,前提是我们要理解何为迭代。

  第一,迭代需要重复进行某一操作

  第二,本次迭代的要依赖上一次的结果继续往下做,如果中途有任何停顿,都不能算是迭代.

  下面来看看几个例子,你就会更能理解迭代的含义。

# example1
# 非迭代 count = 0 while count < 10: print("hello world") count += 1
# example2
# 迭代 count = 0 while count < 10: print(count) count += 1

  例子1,仅仅只是在重复一件事,那就是不停的打印"hello world",并且,这个打印的结果并不依赖上一次输出的值。而例子2,就很好地说明迭代的含义,重复+继续。

2.可迭代对象

  按照上面迭代的含义,我们应该能够知道何为可迭代对象。顾名思义,就是一个对象能够被迭代的使用。那么我们该如何判断一个对象是否可迭代呢?

  Python提供了模块collections,其中有一个isinstance(obj,string)的函数,可以判断一个对象是否为可迭代对象。看下面实例:

代码详解生成器、迭代器
from collections import Iterable

f = open('a.txt')
i = 1
s = '1234'
d = {'abc':1}
t = (1,2,344)
m = {1,2,34,}

print(isinstance(i, Iterable))  # 判断整型是否为可迭代对象
print(isinstance(s, Iterable))  # 判断字符串对象是否为可迭代对象  
print(isinstance(d, Iterable))  # 判断字典对象是否为可迭代对象
print(isinstance(t, Iterable))  # 判断元组对象是否为可迭代对象
print(isinstance(m, Iterable))  # 判断集合对象是否为可迭代对象
print(isinstance(f, Iterable))  # 判断文件对象是否为可迭代对象

########输出结果#########
False
True
True
True
True
True
代码详解生成器、迭代器

  由上面得出,除了整型之外,python内的基本数据类型都是可迭代对象,包括文件对象。那么,python内部是如何知道一个对象是否为可迭代对象呢?答案是,在每一种数据类型对象中,都会有有一个__iter__()方法,正是因为这个方法,才使得这些基本数据类型变为可迭代。 

  如果不信,我们可以来看看下面代码片段:

代码详解生成器、迭代器
f = open('a.txt')
i = 1
s = '1234'
d = {'abc':1}
t = (1,2,344)
m = {1,2,34,}


# hasattr(obj,string) 判断对象中是否存在string方法
print(hasattr(i, '__iter__'))
print(hasattr(s, '__iter__'))
print(hasattr(d, '__iter__'))
print(hasattr(t, '__iter__'))
print(hasattr(m, '__iter__'))
print(hasattr(f, '__iter__'))

#########输出结果#######
C:\Python35\python3.exe D:/CODE_FILE/python/day21/迭代器.py
False
True
True
True
True
True
代码详解生成器、迭代器

相关文章:

  • 2022-12-23
  • 2021-07-24
  • 2021-07-26
  • 2021-06-18
  • 2021-12-09
  • 2021-08-16
猜你喜欢
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
  • 2021-03-31
  • 2021-10-07
相关资源
相似解决方案