0

我试图将 listtwo 中的颜色代码项目(实际上它的三个列表一个用于每种颜色,r,g,b)应用到另一个单词列表....问题是单词多于颜色。结束后如何让颜色代码重新启动?

这是我的代码和到目前为止的尝试......

单词列表....

listone = ["Apple","Toyota","Civic","Merc","Toshiba","Samsung","Dell","Turbo"]

颜色列表

r = [135,147,196,211]
g = [193,208,229,117]
b = [196,35,135,3] 

zippedrgb = zip(r,g,b)

for i, word in enumerate(listone):
    p=0
    y=0
    for x, colour in enumerate(zippedrgb):
        Shape.TextFrame.TextRange.Characters(res[p], charlen[y]).Font.Color = RGB(r[x],g[x],b[x])
        p+=1
        y+=1

当我运行此代码时会发生什么:

从单词列表 - listone - 只有前四个单词收到颜色,其余单词没有任何反应。

我希望我的代码会执行以下操作....

word[1] = RGB(135,193,196)
word[2] = RGB(147,208,35)
word[3] = RGB(196,229,135)
word[4] = RGB(211,117,35)
word[5] = RGB(135,193,196)
word[6] = RGB(147,208,35)
word[7] = RGB(196,229,135)
and so on untill the words finished

如您所见,我希望每次到达结尾时都从头开始颜色,直到单词完成...

我究竟做错了什么?

谢谢...

4

2 回答 2

3

结束后如何让颜色代码重新启动?

itertools.cycle救援:

import itertools

r = [135,147,196,211]
g = [193,208,229,117]
b = [196,35,135,3] 
listone = ["Apple","Toyota","Civic","Merc","Toshiba","Samsung","Dell","Turbo"]
colours = zip(r,g,b)

colours_and_names = zip(listone,itertools.cycle(colours))
#=>  [('Apple', (135, 193, 196)), ('Toyota', (147, 208, 35)), ('Civic', (196, 229, 135)), ('Merc', (211, 117, 3)), ('Toshiba', (135, 193, 196)), ('Samsung', (147, 208, 35)), ('Dell', (196, 229, 135)), ('Turbo', (211, 117, 3))]

现在,让我们稍微修改一下您的代码:

for (i, (word,colour)) in enumerate(colours_and_names):
    Shape.TextFrame.TextRange.Characters(res[i], charlen[i]).Font.Color = RGB(*colour)

您可以看到,通过序列分配,您可以枚举压缩结构,并将元素捕获到变量中;并且*("splat") 运算符允许您将序列解压缩为函数参数。

现在,如果您想要每种颜色的每个单词,您可以使用 product:

list(itertools.product(listone,colours))
#=> [('Apple', (135, 193, 196)), ('Apple', (147, 208, 35)), ('Apple', (196, 229, 135)), ('Apple', (211, 117, 3)), ('Toyota', (135, 193, 196)), ('Toyota', (147, 208, 35)), ('Toyota', (196, 229, 135)), ('Toyota', (211, 117, 3)), ('Civic', (135, 193, 196)), ('Civic', (147, 208, 35)), ('Civic', (196, 229, 135)), ('Civic', (211, 117, 3)), ('Merc', (135, 193, 196)), ('Merc', (147, 208, 35)), ('Merc', (196, 229, 135)), ('Merc', (211, 117, 3)), ('Toshiba', (135, 193, 196)), ('Toshiba', (147, 208, 35)), ('Toshiba', (196, 229, 135)), ('Toshiba', (211, 117, 3)), ('Samsung', (135, 193, 196)), ('Samsung', (147, 208, 35)), ('Samsung', (196, 229, 135)), ('Samsung', (211, 117, 3)), ('Dell', (135, 193, 196)), ('Dell', (147, 208, 35)), ('Dell', (196, 229, 135)), ('Dell', (211, 117, 3)), ('Turbo', (135, 193, 196)), ('Turbo', (147, 208, 35)), ('Turbo', (196, 229, 135)), ('Turbo', (211, 117, 3))]
于 2013-09-18T16:12:35.583 回答
1
from itertools import cycle
list1 = ["Apple","Toyota","Civic","Merc","Toshiba","Samsung","Dell","Turbo"]
list2 = ["Blue","Red"]
print zip(list1,cycle(list2))

或者稍微老式

items = []
for i in range(len(list1)):
    items.append((list1[i],list2[i%len(list2)]))
print items
于 2013-09-18T16:10:55.483 回答