繁体   English   中英

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

[英]Is there a way to loop through a list which is in a for loop in python?

我有这个 Python 程序,它从名为“UserColorIndex”的预定义列表中打印出 colors - 我希望程序打印那些名为“NumberOflesCirc”的变量的 colors。 So if there were 100 in the value for the NumberOfCircles, then the program should print out those colors from the list 100 times, and if the index is only 9 colors, then the program should loop through those colors and repeat through those colors to get他们打印了。 我尝试使用 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

在预期的 output 中,我希望根据 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", "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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM