简体   繁体   中英

Python how to loop with enumerate

I want convert that code from numers ex:

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

to names of animals.

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!")

How to do that, and how delete start() in while loop? I want

if index == max_index: 

refresh loop. That code works with

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

but not work with

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

calling your function start in itself makes infinite loop

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

As @Mark Tolonen commented, I too strongly recommend to not use the start in the if condition to avoid infinite loop

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()

Output:

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!
...

Second Requirement: using while loop

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()

or you can even do it this way

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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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