enumerate
返回一个迭代器( ),它从传递给它的迭代器/迭代器enumerate object
中产生包含索引和项目。tuples
>>> text = 'qwerty'
>>> it = enumerate(text)
>>> next(it)
(0, 'q')
>>> next(it)
(1, 'w')
>>> next(it)
(2, 'e')
>>> list(enumerate(text))
[(0, 'q'), (1, 'w'), (2, 'e'), (3, 'r'), (4, 't'), (5, 'y')]
因此,代码中的列表推导实际上等同于:
>>> text = '12121'
>>> result = []
for item in enumerate(text):
i, ch = item #sequence unpacking
if ch == '1':
result.append(i+1)
...
>>> result
[1, 3, 5]
事实上,您也可以将索引的起点传递给枚举,因此您的列表理解可以更改为:
result = [i for i, ch in enumerate(s, start=1) if ch == '1']
enumerate
通常比这样的东西更受欢迎:
>>> lis = [4, 5, 6, 7]
for i in xrange(len(lis)):
print i,'-->',lis[i]
...
0 --> 4
1 --> 5
2 --> 6
3 --> 7
更好的:
>>> for ind, item in enumerate(lis):
print ind,'-->', item
...
0 --> 4
1 --> 5
2 --> 6
3 --> 7
enumerate
也适用于迭代器:
>>> it = iter(range(5, 9)) #Indexing not possible here
for ind, item in enumerate(it):
print ind,'-->', item
...
0 --> 5
1 --> 6
2 --> 7
3 --> 8
帮助enumerate
:
class enumerate(object)
| enumerate(iterable[, start]) -> iterator for index, value of iterable
|
| Return an enumerate object. iterable must be another object that supports
| iteration. The enumerate object yields pairs containing a count (from
| start, which defaults to zero) and a value yielded by the iterable argument.
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...