擅长:python、mysql、java
<p><a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow noreferrer">^{<cd1>}</a>的语法是<code>range(start, stop, step)</code>。因此,在<code>range(0, len(lst), -1)</code>上迭代将在<code>0</code>上迭代,因为您不能将<code>0</code>降到一个正数。你知道吗</p>
<p>这是可行的,注意我们必须减去1来说明0索引:</p>
<pre><code>for j in range(len(lst)-1, len(lst)-1-value, -1):
lst2.append(lst[j])
print(lst2)
[302, 304, 404, 313, 213, 407, 210]
</code></pre>
<p>这里的<code>range</code>对象有点复杂。注意,负范围和负列表索引工作正常,可以使用<code>range(-1, -value-1, -1)</code>。你知道吗</p>
<p>使用Python,这里根本不需要在范围上循环。相反,可以使用列表切片和<a href="https://docs.python.org/3/library/functions.html#reversed" rel="nofollow noreferrer">^{<cd7>}</a>迭代值本身,而不是索引:</p>
<pre><code>for j in reversed(lst[-value:]):
lst2.append(j)
</code></pre>
<p>当然,这里不需要手动循环,您可以通过<code>+=</code>扩展:</p>
<pre><code>lst2 += reversed(lst[-value:])
</code></pre>
<p>如果您<em>也</em>需要从<code>lst</code>中删除这些项,您可以通过切片来执行此操作:</p>
<pre><code>lst = lst[:-value]
</code></pre>