在Python3中循环遍历数组

时间:2017-03-10 15:06:28

标签: python arrays

假设我有五种不同颜色的列表,colour = ['red', 'blue', ...]等。然后我想创建一个循环,用于制作由tkinter模块定义的任意数量的圆。这意味着类似

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        w.create_oval(x, y, 0, 0, fill='red')

如何为fill='red'部分添加循环,我想要fill=colour[N],其中N会在循环中发生变化?那么第一个圆圈是红色,下一个是蓝色,下一个是绿色等等?我也知道这些重叠,我会尽量使它们不重叠,但这不是问题。

4 个答案:

答案 0 :(得分:3)

我会使用itertools.cycle。 同样,当你将x和y增加100,最多900,使用范围。

from itertools import cycle
colors = ['red', 'blue', 'yellow', 'green', 'orange']

def Circles():
    cycling_colors = cycle(colors)
    for i in range(0, 901, 100):
        w.create_oval(i, i, 0, 0, fill=next(cycling_colors))

答案 1 :(得分:1)

如果要进行嵌套循环,可以使用这种方式:

colours = ['red', 'blue', 'green']

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        for color in colours:
            w.create_oval(x, y, 0, 0, fill=colour)

Circles()

答案 2 :(得分:0)

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        #iterate the colour list
        for colo in colour:
            w.create_oval(x, y, 0, 0, fill=colo) 

希望它有所帮助!

答案 3 :(得分:0)

我假设您可能希望迭代x和y的平面。 至于颜色,同意,循环是颜色的正确方法。

from itertools import cycle
def gen():
   color_cyclist = cycle('red', 'blue', 'green')
   for x in range(0,1000, 100):
       for y in range(0, 1000, 100):
           yield x, y, next(color_cyclist)

for x, y, color in gen():
    w.create(x, y, 0, 0, fill=color)