[英]Is generator.next() visible in Python 3?
我有一個生成系列的生成器,例如:
def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
在 Python 2 中,我可以進行以下調用:
g = triangle_nums() # get the generator
g.next() # get the next value
但是在 Python 3 中,如果我執行相同的兩行代碼,則會出現以下錯誤:
AttributeError: 'generator' object has no attribute 'next'
但是,循環迭代器語法在 Python 3 中確實有效
for n in triangle_nums():
if not exit_cond:
do_something()...
我還沒有找到任何可以解釋 Python 3 行為差異的內容。
如果您的代碼必須在 Python2 和 Python3 下運行,請使用 2to3六庫,如下所示:
import six
six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.