【问题标题】:Is there a way to loop through a list which is in a for loop in python?有没有办法遍历python中for循环中的列表?
【发布时间】:2021-07-14 04:11:51
【问题描述】:

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

【问题讨论】:

  • 您可以尝试使用 mod (%)。 UserColorIndex[i % len(UserColorIndex)]。当循环结束时,这将从 0 重新开始
  • while 似乎更容易。
  • 你会如何使用 while 循环呢?请解释一下,因为我是 Python 新手,并且正在学习 :)
  • 哦,不,我想根据 NumberOfCircles 值重复循环列表。
  • 你检查过你的输出了吗?您似乎希望它循环 18 次。

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


【解决方案1】:

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

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)

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 这里应该使用islice,而不是手动调用next
    猜你喜欢
    • 2010-10-06
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多