Python如何忽略或修复“ IndexError:列表索引超出范围”?

时间:2018-06-23 16:19:13

标签: python loops range

因此,此结果有时可能少于10个答案。我很难弄清楚如何忽略'overbought1'是否小于10。例如,如果只有8个结果,我希望它显示8而忽略不存在的最后两个。

    try:
        for i in range(10):
            (runo[i])
    except:
        pass

    overbought1 = ("Top 10 overbought today: $" + runo[0] + " $" + runo[1] + " $" + runo[2] + " $" + runo[3] + " $" +runo[4] + " $" + runo[5] + " $" + runo[6] + " $" + runo[7]+ " $" + runo[8]+ " $" + runo[9])

    await client.say(overbought1)

1 个答案:

答案 0 :(得分:0)

虽然整个示例毫无意义,但这是避免使用IndexError的方法之一:

for i in range(min(10, len(runo))): # loop at most to the minimum
                                    # between ten and len(runo)
    (runo[i]) # <-- this does nothing here!

另一种方式:

for v in runo[:10]: # access no more than first 10 elements
    v # <-- also does nothing. v is equivalent to runo[i] from the previous loop

现在,如果要修复overbought1字符串,请执行以下操作:

overbought1 = "Top 10 overbought today: $" + " $".join(runo[:10])

甚至:

overbought1 = ("Top %d overbought today: $" % len(runo)) + " $".join(runo[:10])