我有两个数组:
代码:
colors = ["red", "black", "blue",]
string = "Hello World"
def animate():
for i in range(len(string)):
print "{0} - {1}".format(string[i], colors[i%len(colors)])
print "Next iteration..."
#while True:
for i in range(3): # Short example loop - range(3)
animate()
输出:
H - red
e - black
l - blue
l - red
o - black
Next iteration...
H - red
e - black
...
And so on...
目标:每个新的下一次迭代必须以下一个颜色开始,即
H - red # Begins with first color
e - black
l - blue
l - red
o - black
Next iteration...
H - black # Begins with second color
e - blue
...
Next iteration...
H - blue # Begins with third color
e - red
... # Next one begins again with the first.
And so on...
有哪些方法可以修改我的代码? 它只能在 animate 函数中实现吗?我正在考虑python生成器函数( yield ),但是 animate()重置生成器函数的结局循环。
答案 0 :(得分:1)
通过一个柜台,从这个柜台开始你的颜色:
colors = ["red", "black", "blue",]
text = "Hello World"
def animate(counter):
for index, char in enumerate(text):
color_index = (index + counter) % len(colors)
print "{0} - {1}".format(char, colors[color_index])
print "Next iteration..."
#while True:
for i in range(3): # Short example loop - range(3)
animate(i)
输出:
H - red
e - black
l - blue
l - red
o - black
- blue
W - red
o - black
r - blue
l - red
d - black
Next iteration...
H - black
e - blue
l - red
l - black
o - blue
- red
W - black
o - blue
r - red
l - black
d - blue
Next iteration...
H - blue
e - red
l - black
l - blue
o - red
- black
W - blue
o - red
r - black
l - blue
d - red
Next iteration...
答案 1 :(得分:0)
这里有多种方法可以实现您的目标,它当然可以在animate函数内部实现。我假设你想要运行它的次数和颜色一样多吗?我能想到的最简单的方法之一就是递归。
基本纲要是:
这可能不完全清楚,所以我会告诉你我在代码中的含义:
colors = ["red", "black", "blue",]
string = "Hello World"
def animate(location = 0):
for i in range(len(string)):
print "{0} - {1}".format(string[i], colors[(i + location)%len(colors)])
if (location < len(colors) - 1):
print "Next iteration..."
animate(location + 1)
animate()
你可以看到它有效here。请注意,我使用颜色[(i + location)%len(colors)]
拉出显示的颜色如果不清楚,请告诉我。
编辑:仅当您想要仅在animate函数内包含代码时才需要递归。如果您不介意运行循环,您可以像其他答案一样传入计数器。
答案 2 :(得分:0)
Python的itertools.cycle
在这里很有用:
from itertools import cycle
colors = ["red", "black", "blue",]
text = "Hello World"
color = cycle(colors)
def animate():
for c in text:
print '{} - {}'.format(c, next(color))
print "Next iteration..."
for i in range(3): # Short example loop - range(3)
animate()
这将显示以下内容:
H - red
e - black
l - blue
l - red
o - black
- blue
W - red
o - black
r - blue
l - red
d - black
Next iteration...
H - blue
e - red
l - black
l - blue
o - red
- black
W - blue
o - red
r - black
l - blue
d - red
Next iteration...
H - black
e - blue
l - red
l - black
o - blue
- red
W - black
o - blue
r - red
l - black
d - blue
Next iteration...