[英]Python how to loop with enumerate
我想從數字轉換該代碼,例如:
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"]
調用你的 function 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()
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!
...
第二個要求:使用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)
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.