擅长:python、mysql、java
<p>我没有找到比编写一个简单的生成器更优雅、更习惯、更简洁的方法了:</p>
<pre><code>def enumerate2(xs, start=0, step=1):
for x in xs:
yield (start, x)
start += step
</code></pre>
<p>示例:</p>
<pre><code>>>> list(enumerate2([1,2,3], 5, -1))
[(5, 1), (4, 2), (3, 3)]
>>> list(enumerate2([1,2,3], 5, -2))
[(5, 1), (3, 2), (1, 3)]
</code></pre>
<p>如果您不理解上述代码,请阅读<a href="https://stackoverflow.com/questions/231767/the-python-yield-keyword-explained">What does the "yield" keyword do in Python?</a>和<a href="https://stackoverflow.com/questions/2776829/difference-between-python-generators-vs-iterators">Difference between Python's Generators and Iterators</a>。</p>