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/
,如需转载,请注明出处,否则将追究法律责任。