有没有办法循环遍历python中for循环中的列表?

时间:2021-04-20 00:23:29

标签: python python-3.x list for-loop foreach

我有这个 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) 打印列表。我希望它遍历列表。我该怎么做?

2 个答案:

答案 0 :(得分:2)

最简单的方法是使用 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)

答案 1 :(得分:1)

我发现@Tim 的原始解决方案很优雅,@Juanpa 建议的增强功能很有见地。将两者结合会产生以下对我来说似乎非常“Pythonic”的片段:

import itertools

UserColorIndex = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Black", 
"Grey"]

def GenerateRosette(n):
    for color in itertools.islice(itertools.cycle(UserColorIndex), n):
        print(color)

NumberOfCircles = 16
GenerateRosette(NumberOfCircles)