gpt4 book ai didi

Python for 循环返回 IndexError : list index out of range

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:12 27 4
gpt4 key购买 nike

最近才开始学python。我试图在数字列表中找到最小的整数。相反,我收到此错误:

Traceback (most recent call last):
File "H:/Python/untitled/08_python.py", line 32, in <module>
if digits[e] < temp:
IndexError: list index out of range

我知道你可以使用 min(digits) 但我想我会挑战我目前的知识。我很可能犯了一个简单的错误并且没有正确诊断它。如果我在列表中抛出 0,一切正常。

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

low = 0
temp = 0
for e in digits:
if digits[e] < temp:
low = digits[e]
temp = digits[e]

print(low)

最佳答案

for e in digits 直接遍历列表的内容。此时您不需要使用 digits[e],因为 e 已经是值,而不是索引。这也是它失败的原因,因为 digits[10] 超出了列表的末尾。

其他小注意事项 - 您的代码仅适用于正数,因为您从 low = 0 开始;如果列表只有负数,您仍然会得到 0 作为结果。
一种避免这种情况的方法是在开始时将其设置为 None 并同时检查它:

low = None
for e in digits:
if low is None or low < e:
low = e
print(low)

关于Python for 循环返回 IndexError : list index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36290330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com