Python-Ref > Advanced topics > Iterators an generators > Generators in more depth
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Generators in more depth

Expand/Shrink
Zdroj: (generator2-1.py)
  1   def gen_numbers():
  2     yield 1
  3     print "Yielded 1"
  4     yield 2
  5     print "Yielded 2"
  6     for x in range( 3, 10):
  7       yield x
  8       print "Yielded", x
  9   
 10   for x in gen_numbers():
 11     print x
stdout:
1
Yielded 1
2
Yielded 2
3
Yielded 3
4
Yielded 4
5
Yielded 5
6
Yielded 6
7
Yielded 7
8
Yielded 8
9
Yielded 9
Doba běhu: 35.7 ms
Expand/Shrink
Zdroj: (generator2-2.py)
  1   def gen_numbers():
  2     yield 1
  3     print "Yielded 1"
  4     yield 2
  5     print "Yielded 2"
  6     for x in range( 3, 10):
  7       yield x
  8       print "Yielded", x
  9   
 10   g = gen_numbers()
 11   print g
 12   value = g.next()
 13   print value
 14   print "----------"
 15   print g.next()
 16   print "----------"
 17   for x in g:
 18     print x
stdout:
<generator object at 0x2ba4b5be8fc8>
1
----------
Yielded 1
2
----------
Yielded 2
3
Yielded 3
4
Yielded 4
5
Yielded 5
6
Yielded 6
7
Yielded 7
8
Yielded 8
9
Yielded 9
Doba běhu: 27.9 ms