[英]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?如何做到这一点,以及如何在 while 循环中删除 start()? 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调用你的 function
start
本身会产生无限循环
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正如@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()
Output: 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第二个要求:使用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()
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: Output:
Dog 0 Max index: 2
Cat 1 Max index: 2
Rat 2 Max index: 2
Fresh loop!
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.