首页 > 解决方案 > 为什么这个函数需要索引?

问题描述

我已经编写了一个代码来询问狗的年龄,但我试图弄清楚为什么索引是必要的。或者,您能否解释一下索引如何影响代码。谢谢!

def printYoungestDog(DogNames, DogAges):
  index = 0
  minAge = DogAges[0]
  minIndex = 0
  while index < len(DogAges):
    if DogAges[index] < minAge:
      minAge = DogAges[index]
      minIndex = index
    index = index +1
  print('')
  print ("Youngest dog is " + str(DogNames[minIndex])+ " at the still developing age of " + 
  str(minAge))

标签: pythonindexing

解决方案


我假设DogNamesDogAges是两个不同的列表,每个列表中分别包含狗的名字和年龄。

该函数遍历DogAges列表的所有值,并找到最年轻的狗的年龄及其在列表中的索引。该index变量用作索引,每次循环运行时都会增加。当index比列表的长度小一时,循环结束,这意味着它已经遍历了列表中的所有位置。一旦循环完成,它就在列表中找到了年龄最小的索引DogAges。然后它使用这个索引来选择列表中的相应位置DogNames,本质上是年龄最小的狗的名字。然后它会打印出这只狗的名字和它的年龄。


推荐阅读