Python技巧(enumerate)

>>> i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...     seq[i] = '%d: %s' % (i, seq[i])
...     i += 1
...
>>> seq
['0: one', '1: two', '2: three']


>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     seq[i] = '%d: %s' % (i, seq[i])
...
>>> seq
['0: one', '1: two', '2: three']


>>> def _treatment(pos, element):
...     return '%d: %s' %(pos, element)
...
>>> seq = ['one', 'two', 'three']
>>> [_treatment(i, e1) for i, e1 in enumerate(seq)]
['0: one', '1: two', '2: three']


最后一种方式更容易矢量化,因为它共享了基于序列中单个项目的小函数。
每当要对序列中的内容进行循环处理时,就应该尝试用List comprehensions来代替它。

你可能感兴趣的:(enumerate)