假设有一个名为 'my_list
' 和一个名为 ' 的 int 变量list_index
'。基本上,列表'my_list
' 可能会随着时间而改变,因此 'list_index
'可能会提高'IndexError: list index out of range
'。不过,我只是想在发生此错误时进行记录,因为它并不那么重要。为了避免这个错误,我目前的基本解决方案是:
# My first way
if my_list[list_index: list_index +1]:
print('item exists')
else:
print('item does not exist')
# My second way
if -len(my_list) <= list_index < len(my_list):
print('item exists')
else:
print('item does not exist')
除了try/except
声明,是否有其他解决方案来避免“IndexError:列表索引超出范围”错误?
您可以使用 try-except。
a = [1,2,3]
try:
print(a[4])
except IndexError:
pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)