<p>对此没有完整的答案。<code>slice</code>不提供长度,因为结果的长度始终取决于被切片序列的大小,短序列(包括空序列)将生成较少的项,如果<code>slice</code>是无限的,则长度将随着序列的长度而增长;一个<code>slice</code>可能只是通过一个<code>start</code>或<code>stop</code>的<code>None</code>到达序列的末尾。</p>
<p>为了快速简便地计算已知长度序列的长度,只需将<code>.indices</code>与Py3的<code>range</code>(或Py2中的<code>xrange</code>组合,尽管<code>xrange</code>对Py3的值有限制,而Py3的值没有限制)。<a href="https://docs.python.org/3/reference/datamodel.html#slice.indices" rel="nofollow noreferrer">^{<cd12>} gives you the concrete ^{<cd4>}, ^{<cd5>} and ^{<cd15>} values derived when a ^{<cd1>} applies to a sequence of a given length</a>,基本上是您在C样式的<code>for</code>循环中填写的值,该循环与<code>slice</code>循环遍历相同的索引:</p>
<pre><code> for (ssize_t i = start; i < stop; i += stride)
</code></pre>
<p>因此,要计算当应用于包含1000个元素的序列时<code>slice</code>的长度,您需要:</p>
<pre><code>>>> len(range(*slice(0, 2).indices(1000)))
2
>>> len(range(*slice(10, None, 3).indices(1000)))
330
</code></pre>
<p>如果您使用的是Python 2,并且您的值可能超过<code>xrange</code>可以处理的值(它仅限于<code>ssize_t</code>可以容纳的边界和总长度),那么您只需手动进行计算:</p>
<pre><code>def slice_len_for(slc, seqlen):
start, stop, step = slc.indices(seqlen)
return max(0, (stop - start + (step - (1 if step > 0 else -1))) // step)
>>> slice_len_for(slice(10, None, 3), 1000)
330
</code></pre>
<p><strong>更新:</strong>不幸的是,<code>slice.indices</code>本身不会接受超过<code>long</code>所能容纳的序列的<code>len</code>,因此这不会使您在Py2中使用<code>xrange</code>获得任何好处。为那些感兴趣的人留下了位置,但是解决方法不会解决任何问题,除非你也<a href="https://github.com/python/cpython/blob/2.7/Objects/sliceobject.c#L102" rel="nofollow noreferrer">perform the work ^{<cd1>} does to convert negative values and ^{<cd6>} to concrete values based on the sequence length.</a>叹息。</p>