gpt4 book ai didi

Python:将for循环与列表相关联

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:39 24 4
gpt4 key购买 nike

我找不到任何解决方法。在我的真实示例中,这将用于将颜色蒙版与对象相关联。

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

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)]

zip()itertools.cycle() :

from itertools import cycle

for n, (obj, color) in enumerate(zip(objects, cycle(colors))):
print n, obj, color

演示:

>>> 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

关于Python:将for循环与列表相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com