Implementing a generator/yield in a Python C extension

jieforest發表於2012-08-15
In Python, a generator is a function that returns an iterator object. There are a couple of ways to do this, but the most elegant and common one is to use the yield statement.

For example, here is a simple synthetic example:

CODE:

def pyrevgen(seq):
    for i, elem in enumerate(reversed(seq)):
        yield i, elemThe pyrevgen function is a generator. Given any sequence, it returns an iterator that yields the sequences’s elements in reversed order, and also enumerates them. For example:

CODE:

>>> for i, e in pyrevgen(['a', 'b', 'c']):
...   print(i, e)
...
0 c
1 b
2 a

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-741022/,如需轉載,請註明出處,否則將追究法律責任。

相關文章