ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Implementing a generator/yield in a Python C extension

Implementing a generator/yield in a Python C extension

原创 Linux操作系统 作者:jieforest 时间:2012-08-15 09:50:46 0 删除 编辑
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博客 ” ,链接:https://blog.itpub.net/301743/viewspace-741022/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    441
  • 访问量
    602351