难以使用Itertools循环

时间:2012-08-31 01:43:47

标签: python list itertools turtle-graphics

目前,我使用Turtlebegin_poly以及end_polyregister_shape中定义了许多形状。我希望能够将所有这些值放入列表中,只需按一下按钮,循环显示列表,从而更改Turtle形状。我很难通过Itertools实现这一目标,并且想知道如何实现这一目标。

编辑:我最终将它工作,我将所有值附加到列表中,然后使用计数器选择要转到的索引。

1 个答案:

答案 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