【问题标题】:skipping over IndexError in for loop在 for 循环中跳过 IndexError
【发布时间】: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)并获取找到的值?

【问题讨论】:

标签: python python-2.7 for-loop indexing


【解决方案1】:

你应该检查有效的索引:

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

【讨论】:

    【解决方案2】:

    您正在这里寻找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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      相关资源
      最近更新 更多