Python:将for循环与列表相关联
我找不到任何解决办法。在我的真实示例中,这将用于将颜色遮罩与对象关联 我认为最好的解释方式是举个例子:Python:将for循环与列表相关联,python,list,loops,for-loop,Python,List,Loops,For Loop,我找不到任何解决办法。在我的真实示例中,这将用于将颜色遮罩与对象关联 我认为最好的解释方式是举个例子: 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 我需要的结果是: #0 pencil
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
我需要的结果是:
#0 pencil # 0 red
#1 pen # 1 green
#2 keyboard # 2 blue
#3 table # 0 red
#4 phone # 1 green
因此,始终会有3种颜色与对象关联,如何在python中的for
循环中获得此结果?每次n(迭代器)大于颜色列表的长度时,我如何告诉它返回并打印第一个索引,依此类推?使用%
:
for n, obj in enumerate(objects):
print n, obj, colors[n % len(colors)]
或及:
演示:
或
>>> for i, obj, j, color in izip(count(), objects, cycle(range(len(colors))), cycle(colors)):
... print i, obj, j, color
...
0 pencil 0 red
1 pen 1 green
2 keyboard 2 blue
3 table 0 red
4 phone 1 green
>>> 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
>>> from itertools import count, izip, cycle
>>> objects = ['pencil','pen','keyboard','table','phone']
>>> colors = ['red','green','blue']
>>> for i, obj, color in izip(count(), objects, cycle(colors)):
... print i, obj, color
...
0 pencil red
1 pen green
2 keyboard blue
3 table red
4 phone green
>>> for i, obj, j, color in izip(count(), objects, cycle(range(len(colors))), cycle(colors)):
... print i, obj, j, color
...
0 pencil 0 red
1 pen 1 green
2 keyboard 2 blue
3 table 0 red
4 phone 1 green