2015-11-04 146 views
0

如何跳过错误“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)并获取找到的值?

+0

你有没有考虑过['try-except'](https://docs.python.org/2/tutorial/errors.html#handling-exceptions)? – ricky3350

回答

0

您应该检查有效指标:

for i in my_items: 
    position = bisect(thelist, i) 
    if position < len(thelist): 
    found_list.append(thelist[position]) 
    found_values.append(thevalues[position]) 
0

你要找的try-except这里。这是一种管理控制流的方法,它允许您尝试执行可能会引发错误的操作(如IndexError)并执行一些清理。它看起来是这样的:

for i in my_items: 
    try: 
     position = bisect(thelist, i) 
     found_list.append(thelist[position]) 
     found_values.append(thevalues[position]) 
    except IndexError: 
     print('{0} is not in thelist'.format(position)) 

作为一个副作用,这实际上是Pythonic。如果您有兴趣了解更多关于使用try-except来管理控制流的信息,请查看this blog-post