常çå°å«äººä½¿ç¨æ讨论yieldè¯æ³,è½æå°çä¸æ解éå´ä¸å¤,ä»å¤©å³å¿æå®yield,æææ¶çç解贴å°è¿é.
æå®yieldä¹å: å 代å¨(iterator)
åç°yield: çæå¨(constructor)
使ç¨yield: éå½è°ç¨
1. iterator
å 代å¨æç®åä¾ååºè¯¥æ¯æ°ç»ä¸æ äºï¼ä¸çä¸é¢çc++代ç ï¼
int array[10];
for ( int i = 0; i < 10; i++ )
printf("%d ", array[i]);
å 代å¨å·¥ä½å¨ä¸ä¸ªå®¹å¨é(array[10])ï¼å®æä¸å®é¡ºåº(i++)ä»å®¹å¨éååºå¼(array[i])并è¿è¡æä½(printf("%d ", array[i])ã
ä¸é¢ç代ç ç¿»è¯æpythonï¼
array = [i for i in range(10)]
for i in array:
print i,
for i in arrayå¹²äºä»ä¹(å«ä¹±æ³)ï¼é¦å
ï¼arrayä½ä¸ºä¸ä¸ªlistæ¯ä¸ªå®¹å¨ï¼å
¶æ¬¡listè¿ä¸ªå
建类åæé»è®¤çnextè¡ä¸ºï¼pythonåç°è¿äºä¹åé åçç§å¯ç没被åä½çå°çå¨ä½æ¯ï¼æ¿åºarrayè¿ä¸«å®¹å¨çå 代å¨ï¼ä»éé¢nextä¸ä¸æå¼ç»iä¾for循ç¯ä¸»ä½å¤ç½®ï¼foræè¿ä¸ªå¼printäºã
ç°å¨çé®é¢æ¯æ°æ®å¯ä»¥å容å¨å 代ï¼ä»£ç å¯ä»¥åï¼
æä¹ä¸è¡ï¼ç¢ç¢å¯ä»¥ç¨æ¥æ¾èï¼wk们ä¸å°±èæ³åºç¨ntçåï¼å½ç¶æ们çyieldä¸ä¼é£ä¹yellow + bt
2. constructor
æä¹æå½æ°åæconstructorï¼ å¨å½æ°ä½éæyieldå°±è¡äºï¼
def gen():
print 'enter'
yield 1
print 'next'
yield 2
print 'next again'
for i in gen():
print i
åä½ï¼pythonçå°genå½æ°éåºç°yieldï¼ç¥éå¯ä»¥ç¨nextäºï¼é®é¢æ¯æä¹å¯¹ä»£ç è¿ä¸ªå®¹å¨ç©nextï¼
ä»å®¹å¨éæ¿å°iteratorçæ¶åå®è¿ä»ä¹ä¹ä¸æ¯ï¼å¤å¨å®¹å¨å
¥å£å¤ï¼å¯¹äºæ°ç»æ¥è¯´å°±æ¯ä¸æ 为-1çå°æ¹ï¼å¯¹äºå½æ°æ¥è¯´å°±æ¯å½æ°å
¥å£åäºæ²¡å¹²ï¼ä½æ¯ä¸äºä¿±å¤å°±æ¬ nextã
å¼å§for i in gï¼next让itreatorç¬è¡å°yieldè¯å¥åå¨çå°æ¹å¹¶è¿åå¼,
å次nextå°±åç¬å°ä¸ä¸ä¸ªyieldè¯å¥åå¨çå°æ¹å¹¶è¿åå¼,ä¾æ¬¡è¿æ ·ç´å°å½æ°è¿å(容å¨å°½å¤´)ã
æ¨ä¸å®çåºæ¥ä¸é¢ä»£ç çè¾åºæ¯ï¼
enter
1
next
2
next again
å¦æ没çåºæ¥è¯·ä¸è¦å¾ä¸çäºå
å¾å被yieldæå®ã
3. 使ç¨yield
yieldç代ç å 代è½åä¸ä½è½ææå½æ°æ§è¡è¿è½è®°ä¸æç¹å¤çæ°æ®ï¼ä¸æ¬¡next书æ¥ä¸åï¼è¿æ£æ¯éå½å½æ°éè¦çã
ä¾å¦ä¸åºéåäºåæ ï¼
(åºè¯¥æ¯David Mertzåç)
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
for n in inorder(tree)
print n
å½ç¶yieldè¿ç§ä»£ç nextçè½åè¿å¯ä»¥ç¨å¨å
¶å®æ¹é¢ï¼åç°ææ¡çå¨è´´å¯ã
温馨提示:答案为网友推荐,仅供参考