如何跳过错误“IndexError:列表索引超出范围”并继续处理剩余的for循环?例如,我有:跳过for循环中的IndexError
from bisect import bisect
thelist = [1, 2, 3, 6, 7, 8, 9]
thevalues = [.1, .2, .3, .6, .7, .8, .9]
my_items = [10, 1, 9, 4, 3]
found_list = []
found_values = []
for i in my_items:
position = bisect(thelist, i)
found_list.append(thelist[position])
found_values.append(thevalues[position])
所需的输出:
found_list = [1, 9, 3]
found_values = [.1, .9, .3]
但自10不在“的thelist”我通过循环得到一个错误第一次。即使“my_items”中的值不在“列表”中,我是否可以跳过这些(以一种有效的方式,无需更改my_list)并获取找到的值?
你有没有考虑过['try-except'](https://docs.python.org/2/tutorial/errors.html#handling-exceptions)? – ricky3350