歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中的生成器和迭代器

Python中的生成器和迭代器

日期:2017/3/1 9:33:00   编辑:Linux編程

個人覺得iterator和yield實現的是相同的功能,只不過iterator需要在類中實現,yield實在函數中實現,二者均會保存狀態

生成器也是由迭代器實現的

#!/usr/bin/env python
#coding: utf-8
#定義三個函數
def Lee(name,age):
return 'I am %s,I am %d old' %(name,age)

def Marlon():
return 'I am Marlon'

def Allen():
return 'I am Allen'

function_list= [Lee,Marlon,Allen] #有三個函數的列表

#定義一個生成器
def MyGenerator(*args):
for i in args:
yield i

a=MyGenerator(*function_list) #生成器
print apply(a.next(),('Lee',29)) #執行next()方法,這時會保存現在的執行狀態,下一次調用next()方法時,會用到此狀態
print apply(a.next())
print apply(a.next())

#為什麼yield有next方法? 看下面迭代器的列子,就會明白為什麼生成器是由迭代器實現的
#下面是迭代器的例子, 一個類如果實現了__iter__方法,和next()方法,就叫做迭代器
class MyIterator(object):
def __init__(self,funcs):
self.total_funcs=len(funcs)#記錄總共需要執行多少個函數
self.func_list=funcs #記錄所有函數
self.step = 0 #記錄當前執行到哪一個函數
def __iter__(self):
pass
def next(self):
if self.step < self.total_funcs: #當目前所執行的函數所在的位置小於總的函數個數時
self.step+=1 #step
return self.func_list[self.step-1] #執行當前函數
else:
raise StopIteration

c=MyIterator(function_list)
print apply(c.next(),('Lee',29))
print apply(c.next())
print apply(c.next())

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved