擅长:python、mysql、java
<p>您应该添加<code>try</code>{<cd2>},它将捕获索引错误,并执行有助于解决该错误的操作</p>
<pre><code>for n in range(100):
try:
Num = random.choice(listNum)
print(Num)
del listNum[0:Num]
print(listNum)
except IndexError: # this will handle only IndexError, don't use pure except
break # stop loop when there are no more numbers
</code></pre>
<p>其他一些更聪明的解决方案是:</p>
<pre><code>while len(listNum):
# do same stuff here
# print number only when list has at least 1 element
</code></pre>
<p>另外,请记住,您的列表越来越小,因此您不能只<code>del [0: Num]</code></p>