<p>由于检查内部<code>while</code>循环中条件的顺序,代码有时会获得越界索引。在</p>
<p>通常,调试此类问题的最佳方法是向代码中添加<code>try</code>和<code>except</code>块,并使用<code>except</code>块打印出有用的诊断值。关于这个问题的循环I:</p>
<pre><code>try:
while(n[i]<=n[lt] and i<=gt):
if(x!=n[lt]):
print("alert!!!")
if(n[i]<n[lt]): #current alement not a duplicate of partitioning alement
if(lt<=i):
n[lt],n[i]=n[i],n[lt]
#print(n)
i+=1
lt+=1
else: #current element is a duplicate partitioning alement
#print(n[i],"=",n[lt])
i+=1
except IndexError:
print(i, gt, len(n))
raise
</code></pre>
<p>您将看到在某些情况下,<code>gt</code>将是<code>len(n) - 1</code>,而{<cd7>}将是{<cd8>}。在这种情况下,<code>while(n[i]<=n[lt] and i<=gt):</code>中的第一个测试将引发一个<code>IndexError</code>,因为{<cd11>}不是有效的索引。在</p>
<p>相反,您应该将测试放在另一个顺序中,首先是<code>i <= gt</code>。如果该测试是<code>False</code>,则{<cd14>}将“短路”而不评估第二个测试,第二个测试是导致异常的测试。所以:使用<code>while i <= gt and n[i] <= n[lt]:</code>(括号是不必要的,所以我删除了它们,并将这些术语与运算符隔开。有关Python样式的更多建议,请参见<a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>。)</p>