python - 为什么这个函数需要索引?
问题描述
我已经编写了一个代码来询问狗的年龄,但我试图弄清楚为什么索引是必要的。或者,您能否解释一下索引如何影响代码。谢谢!
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))
解决方案
我假设DogNames
和DogAges
是两个不同的列表,每个列表中分别包含狗的名字和年龄。
该函数遍历DogAges
列表的所有值,并找到最年轻的狗的年龄及其在列表中的索引。该index
变量用作索引,每次循环运行时都会增加。当index
比列表的长度小一时,循环结束,这意味着它已经遍历了列表中的所有位置。一旦循环完成,它就在列表中找到了年龄最小的索引DogAges
。然后它使用这个索引来选择列表中的相应位置DogNames
,本质上是年龄最小的狗的名字。然后它会打印出这只狗的名字和它的年龄。
推荐阅读
- ios - 解码 JSON 时在两个结构中使用相同的编码键
- pascal - 为什么乘法时会抛出异常?
- gcc - How to make GCC not generate .idata section?
- selenium - How to find element by xpath in shadow dom
- php - Headers/footers and paging not exported with mPDF and PHPExcel?
- c# - Azure 函数:异步方法和输出参数
- javascript - Override .css stylesheet file (not inline)
- python - How to remove one of the dummy variables in regression
- r - 用第一个非 NA 填充 data.frame 中的 NA
- c# - Linq2Db and string.join()