目前,我使用Turtle
和begin_poly
以及end_poly
在register_shape
中定义了许多形状。我希望能够将所有这些值放入列表中,只需按一下按钮,循环显示列表,从而更改Turtle
形状。我很难通过Itertools
实现这一目标,并且想知道如何实现这一目标。
编辑:我最终将它工作,我将所有值附加到列表中,然后使用计数器选择要转到的索引。
答案 0 :(得分:28)
首先,创建生成器:
>>> 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