python iter()的使用 迭代器 生成器的使用

废话不多说  直接上代码:

s=iter('12345')
print 's.next(): ', s.next()
print 'type(s.next()):' ,  type(s.next())

print 's.next(): ', s.next()

print 'type(s):' , type(s)


dic ={ 'a':'c','b':'c'}
d=iter(dic)
print 'dic= ',dic
print 'type(d): ',type(d)
print 'd.next(): ' ,d.next()

结果:

s.next():  1
type(s.next()): <type 'str'>
s.next():  3
type(s): <type 'iterator'>
dic=  {'a': 'c', 'b': 'c'}
type(d):  <type 'dictionary-keyiterator'>
d.next():  a

  

 字典的迭代器会遍历他的键。

for eachKey in dict.keys():   ====== 等于=======for eachKey in dict

文件迭代器会自动调用readline()方法。

myFile = open(filename)

for eachline in myFile:

    print eachline

可变对象的迭代器,如列表、字典,使用时后不能更改元素的值。

列表解析: [len(word) for line in file for word in line.split()]

不足:列表解析必须生成所有的数据,用于创建整个列表,这可能会对有大量数据的迭代器有负面效应。

生成器表达式 可以通过列表解析和生成器解决这个问题。

生成器并不真正创建数字列表,二是返回一个生成器,这个生成器在每次计算出一个条目后,把这个条目"产生(yeild)"出来。生成器表达式使用了”延迟计算(lazy evaluation)“,所以它在使用内存上更有效。

与列表解析在形式上的差别仅在于一个是[]一个是()。

 生成器表达式:

   max(len(x.strip()) for x in open(file))

生成器:

   从语法上讲,生成器是一个带yield语句的函数。一个函数或者子程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果——那就是yeild语句的功能,返回一个值给调用者并暂停执行。当生成器的next()的方法被调用的时候,它会准确地从离开的地方继续。

原文地址:https://www.cnblogs.com/TianMG/p/3098429.html