【发布时间】:2016-02-05 12:25:50
【问题描述】:
如何跳过错误“IndexError: list index out of range”并继续执行剩余的 for 循环?例如我有:
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' 中的值不在 'thelist' 中,我是否可以跳过这些(以一种省时的方式并且无需更改 my_list)并获取找到的值?
【问题讨论】:
-
你考虑过
try-except吗?
标签: python python-2.7 for-loop indexing