generator

生成器

>>> def gen123():
...     print "yield to 1"
...     yield 1
...     print "yield to 2"
...     yield 2
...     print "yield to 3"
...     yield 3
... 
>>> g = gen123()
>>> next(g)
yield to 1
1
>>> next(g)
yield to 2
2
>>> next(g)
yield to 3
3
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
>>> for v in gen123():
...     print v
... 
yield to 1
1
yield to 2
2
yield to 3
3


生成器的对象是相互独立的

>>> h = gen123()
>>> i = gen123()
>>> h
<generator object gen123 at 0x7fefcf2e76e0>
>>> i
<generator object gen123 at 0x7fefcbe85960>

打印一次

In [4]: def distinct(iterable):
   ...:     a = set()
   ...:     for item in iterable:
   ...:         if item in a:
   ...:             continue
   ...:         yield item
   ...:         a.add(item)
   ...:         

In [5]: items = [1,3,4,3,9,1]

In [6]: for item in distinct(items):
   ...:     print(item)
   ...:     
1
3
4
9

 

阅读更多
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭