Python:将循环与列表相关联

use*_*661 3 python loops for-loop list

我找不到任何解决方法.在我的实例中,这将用于将颜色遮罩与对象相关联.

我认为最好的解释方法是举个例子:

objects = ['pencil','pen','keyboard','table','phone']
colors  = ['red','green','blue']

for n, i in enumerate(objects):
    print n,i #0 pencil

    # print the index of colors
Run Code Online (Sandbox Code Playgroud)

我需要的结果:

#0 pencil    # 0 red
#1 pen       # 1 green
#2 keyboard  # 2 blue
#3 table     # 0 red
#4 phone     # 1 green
Run Code Online (Sandbox Code Playgroud)

因此,总会有3种颜色与对象相关联,如何for在python循环中获得此结果?每次n(迭代器)大于颜色列表的长度时,如何告诉它返回并打印第一个索引,依此类推?

Mar*_*ers 8

用途%:

for n, obj in enumerate(objects):
    print n, obj, colors[n % len(colors)]
Run Code Online (Sandbox Code Playgroud)

zip()itertools.cycle():

from itertools import cycle

for n, (obj, color) in enumerate(zip(objects, cycle(colors))):
    print n, obj, color
Run Code Online (Sandbox Code Playgroud)

演示:

>>> objects = ['pencil','pen','keyboard','table','phone']
>>> colors  = ['red','green','blue']
>>> for n, obj in enumerate(objects):
...     print n, obj, colors[n % len(colors)]
... 
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green
>>> from itertools import cycle
>>> for n, (obj, color) in enumerate(zip(objects, cycle(colors))):
...     print n, obj, color
... 
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green
Run Code Online (Sandbox Code Playgroud)