不确定这是因为 Jupyter Notebook 还是 Python 处理了异常,但我正在和 friend 一起解决一个涉及算法的问题
在编写代码时,我使用了 Python!
exampleList = ['a', 'b', 'c', 'd', 'e']
for i in range(0, len(exampleList)):
for j in range(i + 1, len(exampleList)):
print(exampleList[i], exampleList[j])
基本上,争论是......这段代码(类似的代码,我用一个简单的例子来说明)涉及两个 for
循环必须抛出错误!因为,索引 i
达到了 len(exampleList) - 1
,而索引 j
技术上将变为 len(exampleList)
那时,print(exampleList[i], exampleList[j])
无法工作!看起来在运行代码时,它确实打印得很完美,而且我认为可以处理 IndexError: list index out of range
异常!
我的问题是.. 这应该是 Python 中的预期行为吗?因为和我辩论的那个人最后告诉我‘进行你采访的人注意到了这些事情!你必须能够解释每一行。”
我想了解这部分是如何处理的,这样我就可以解释为什么这不会引发错误!
最佳答案
range
函数包含下限,但不包含上限。
您的示例列表有 5 个元素。这意味着第一个循环正在运行 range(0,5)
,使最大值 i=4
。这使得第二个循环的最大值为 range(5,5)
,这是一个空列表。迭代空列表会导致 0 次迭代。
>>> exampleList = ['a', 'b', 'c', 'd', 'e']
>>> len(exampleList)
5
>>> range(0, 5)
[0, 1, 2, 3, 4]
>>> range(5,5)
[]
关于Python - 索引错误 : list index out of range NOT being thrown when it should be,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382748/