因此,此结果有时可能少于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)
答案 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])