Python 如何使用枚举循环

Python how to loop with enumerate

我想从数字 ex 转换该代码:

animal = ["Dog1","Dog2","Dog3"]

到动物的名字。

def start():
    animal = ["Dog","Cat","Bird"]
    index = 0
    max_value = max(animal)
    max_index = animal.index(max_value)
    for index, animal in enumerate(animal):
        while True:
            if index <= max_index:
                print(animal, index, "Max index: ",max_index)
            break
    start()    
    print("Fresh loop!")

如何做到这一点,以及如何删除 while 循环中的 start()?我要

if index == max_index: 

刷新循环。 该代码适用于

["Dog1","Dog2","Dog3"] 

但不适用于

["Dog","Cat","Bird"]

调用你的函数start 本身会造成无限循环

if index == max_index:
            print("Fresh loop!")
            start()      

正如@Mark Tolonen 评论的那样,我强烈建议不要在 if 条件中使用 start 以避免无限循环

def start():
    animal = ["site1","site2","site3"]
    index = 0
    max_value = max(animal)
    max_index = animal.index(max_value)
    for index, animal in enumerate(animal):
        print(animal, index, "Max index: ",max_index)
        if index == max_index:
            print("Fresh loop!")
            start()

start()

输出:

site1 0 Max index:  2
site2 1 Max index:  2
site3 2 Max index:  2
Fresh loop!
site1 0 Max index:  2
site2 1 Max index:  2
site3 2 Max index:  2
Fresh loop!
...

第二个要求:使用 while 循环

def start():
    animal = ["Dog", "Cat", "Rat"]
    index = 0
    max_value = max(animal)
    max_index = animal.index(max_value)
    while index <= max_index:
        print(animal[index], index, "Max index: ",max_index)
        index = index + 1
        if index == len(animal):
            print("Fresh loop!")
            index = 0

start()

或者您甚至可以这样做

def start(animal):
    index = 0
    max_value = max(animal)
    max_index = animal.index(max_value)
    while index <= max_index:
        print(animal[index], index, "Max index: ",max_index)
        index = index + 1
        if index == len(animal):
            print("Fresh loop!")
            index = 0

animal = ["Dog", "Cat", "Rat"]
start(animal)

输出:

Dog 0 Max index:  2
Cat 1 Max index:  2
Rat 2 Max index:  2
Fresh loop!
...