<pre><code>$ python
Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> a = collections.OrderedDict({'a':'1','b':'2'})
>>> a
OrderedDict([('a', '1'), ('b', '2')])
>>> for i, (k,v) in enumerate(a.iteritems()):
... print i, k, v
...
0 a 1
1 b 2
</code></pre>
<p>是丑陋的,如果你问我的话。</p>
<p>我不知道你为什么对索引感兴趣。
迪克特之间的想法是你要对索引一无所知。
dict和队列背后有很多逻辑,这样我们就不用索引了。</p>
<p>如果坚持要获取索引,则不需要重复两次。</p>
<p>让我们看看枚举对列表做了什么:</p>
<pre><code>>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
</code></pre>
<p>注意“开始”。</p>
<p>枚举知道如何管理列表。字典将数据存储为一个列表,放在野兽的肚子里。那么,如果我们在一个dict上使用枚举,会发生什么呢?</p>
<pre><code>>>> for i,k in enumerate(a):
... print i,k
...
0 a
1 b
</code></pre>
<p>在这种情况下,我会选择优雅的:</p>
<pre><code>>>> for i,k in enumerate(a):
... print i,k,a[k]
...
0 a 1
1 b 2
</code></pre>
<p>我觉得“对我来说,(k,v)in”太快暴露了太多的内在结构。
有了“for i,k in”,我们就得到了保护,当需要重构时,我们不需要接触循环的方式。我们只需要改变我们在循环中所做的事情。少了一个需要注意的方面。</p>
<p>更不用说这个枚举调用在2.6之后的任何python中的工作方式都是一样的:)</p>
<p><a href="https://docs.python.org/2/library/stdtypes.html#dict.iteritems" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#dict.iteritems</a></p>
<p><a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow">https://docs.python.org/2/library/functions.html#enumerate</a></p>