Difficulty using Itertools cycle
17,372
First, create the generator:
>>> import itertools
>>> shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"]
>>> g = itertools.cycle(shape_list)
Then call next()
whenever you want another one.
>>> next(g)
'square'
>>> next(g)
'triangle'
>>> next(g)
'circle'
>>> next(g)
'pentagon'
>>> next(g)
'star'
>>> next(g)
'octagon'
>>> next(g)
'square'
>>> next(g)
'triangle'
Here's a simple program:
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
Output:
Drawing square
Drawing triangle
Drawing circle
Drawing pentagon
Drawing star
Drawing octagon
Drawing square
Drawing triangle
Author by
Hayden
Updated on July 15, 2022Comments
-
Hayden almost 2 years
At the moment I have defined many shapes in
Turtle
usingbegin_poly
andend_poly
thenregister_shape
. I want to be able to put all of these values into a list and, with a press of a button, cycle through the list hence changing theTurtle
shape. I am having difficulty achieving this withItertools
and was wondering for some assistance on how I could achieve this.Edit: I got it working in the end, I appended all the values into a list then used a counter to choose which index to go to.
-
Hayden over 11 yearsI tried what I did in the edited question but it still isn't working. :S
-
Marcin over 11 years-1 how does this take OP beyond what they have in the question?
-
DSM over 11 years@Marcin: Most of the code in the question is from this answer. Originally it seemed like the OP was constructing a new
cycle
instance every time, although it's hard to tell fromnext (itertools.cycle (shape_list)) 1 next (itertools.cycle (shape_list)) 2
, whatever that might mean. This answer separated out the generator creation from the getting of the next element, which was a perfectly plausible reading of the OP's problem. -
Hayden over 11 yearsUnfortunately Mark the code still doesn't work. :( Am I doing something wrong?
-
Mark Tolonen over 11 years@Marcin, the OP has edited his question. As DSM says the original question wasn't clear.
-
richar8086 over 7 years
g.next()
doesn't work in Python 3: AttributeError: 'itertools.cycle' object has no attribute 'next' You need to callnext(g)