如何解决有没有办法循环遍历python中for循环中的列表?
我有这个 Python 程序,它从名为“UserColorIndex”的预定义列表中打印出颜色——我希望该程序根据名为“NumberOfCircles”的变量的数值来打印这些颜色。因此,如果 NumberOfCircles 的值中有 100,那么程序应该从列表中打印出这些颜色 100 次,如果索引只有 9 种颜色,那么程序应该遍历这些颜色并重复这些颜色以获得他们打印。我尝试使用 enumerate 方法,但这只是创建了不同的数据类型。我将如何修复/执行此操作?
这是我的代码:
NumberOfCircles = 18 # I don't kNow,just some random number,the program should work regardless of which number is placed
def GenerateRosette():
for i in range(NumberOfCircles):
print(UserColorIndex[i])
UserColorIndex = ["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Black","Grey"]
GenerateRosette()
Output:
________________
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Black
Grey
Traceback (most recent call last):
File "file.py",line 9,in <module>
GenerateRosette()
File "file.py",line 5,in GenerateRosette
print(UserColorIndex[i])
IndexError: list index out of range
EXPECTED Output (What I want):
________________
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Black
Grey
Red
Orange
Yellow
Green
Blue
Indigo
Violet
Black
Grey
在预期的输出中,我希望根据 for 循环的运行次数 (NumberOfCircles) 打印列表。我希望它遍历列表。我该怎么做?
解决方法
最简单的方法是使用 itertools.cycle:
import itertools
UserColorIndex = ["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Black","Grey"]
def GenerateRosette(n):
color = itertools.cycle(UserColorIndex)
for _ in range(n):
print(next(color))
NumberOfCircles = 16
GenerateRosette(NumberOfCircles)
,
我发现@Tim 的原始解决方案很优雅,@Juanpa 建议的增强功能很有见地。将两者结合会产生以下对我来说似乎非常“Pythonic”的片段:
import itertools
UserColorIndex = ["Red","Grey"]
def GenerateRosette(n):
for color in itertools.islice(itertools.cycle(UserColorIndex),n):
print(color)
NumberOfCircles = 16
GenerateRosette(NumberOfCircles)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。