まず、ジェネレーターを作成します。
>>> import itertools
>>> shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
>>> g = itertools.cycle(shape_list)
次に、next()
別のものが必要なときにいつでも呼び出します。
>>> next(g)
'square'
>>> next(g)
'triangle'
>>> next(g)
'circle'
>>> next(g)
'pentagon'
>>> next(g)
'star'
>>> next(g)
'octagon'
>>> next(g)
'square'
>>> next(g)
'triangle'
簡単なプログラムを次に示します。
import itertools
shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
g = itertools.cycle(shape_list)
for i in xrange(8):
shape = next(g)
print "Drawing",shape
出力:
Drawing square
Drawing triangle
Drawing circle
Drawing pentagon
Drawing star
Drawing octagon
Drawing square
Drawing triangle