How to get the index of the iterator object?
This question already has an answer here:
Iterators were not designed to be indexed (remember that they produce their items lazily).
Instead, you can use enumerate
to number the items as they are produced:
for index, match in enumerate(it):
Below is a demonstration:
>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it):
... print(index, item)
...
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
>>>
Note that you can also specify a number to start the counting at:
>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it, 1): # Start counting at 1 instead of 0
... print(index, item)
...
1 10
2 11
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 19
>>>
链接地址: http://www.djcxy.com/p/24006.html
下一篇: 如何获得迭代器对象的索引?