<p>假设我有一个项目列表,我想遍历其中的前几个:</p>
<pre><code>items = list(range(10)) # I mean this to represent any kind of iterable.
limit = 5
</code></pre>
<h2>天真的实现</h2>
<p>来自其他语言的Python naïf可能会编写这种完全可服务且性能良好(如果是单体的话)的代码:</p>
<pre><code>index = 0
for item in items: # Python's `for` loop is a for-each.
print(item) # or whatever function of that item.
index += 1
if index == limit:
break
</code></pre>
<h2>更惯用的实现</h2>
<p>但是Python已经枚举了,它很好地包含了大约一半的代码:</p>
<pre><code>for index, item in enumerate(items):
print(item)
if index == limit: # There's gotta be a better way.
break
</code></pre>
<p>所以我们要把额外的代码减半。但总有更好的办法。</p>
<h2>我们能估计一下下面的伪代码行为吗?</h2>
<p>如果enumerate采用了另一个可选的<code>stop</code>参数(例如,它采用了这样的<code>start</code>参数:<code>enumerate(items, start=1)</code>),我认为这是理想的,但下面的参数不存在(请参见<a href="https://docs.python.org/3/library/functions.html#enumerate" rel="noreferrer">documentation on enumerate here</a>):</p>
<pre><code># hypothetical code, not implemented:
for _, item in enumerate(items, start=0, stop=limit): # `stop` not implemented
print(item)
</code></pre>
<p>注意,不需要命名<code>index</code>,因为不需要引用它。</p>
<p>有没有一种惯用的方法来写上面的东西?怎样?</p>
<p>第二个问题:为什么不将其内置到枚举中?</p>
<p>为什么不简单地使用</p>
<pre><code>for item in items[:limit]: # or limit+1, depends
print(item) # or whatever function of that item.
</code></pre>
<p>这只适用于一些iterable,但是由于您指定了列表,所以它可以工作。</p>
<p>如果你使用集合或听写等,它就不起作用</p>