Creating a counter inside a Python for loop
This question already has an answer here:
This (creating an extra variable before the for-loop) is not pythonic .
The pythonic way to iterate over items while having an extra counter is using enumerate
:
for index, item in enumerate(iterable):
print(index, item)
So, for example for a list lst
this would be:
lst = ["a", "b", "c"]
for index, item in enumerate(lst):
print(index, item)
...and generate the output:
0 a
1 b
2 c
You are strongly recommended to always use Python's built-in functions for creating "pythonic solutions" whenever possible. There is also the documentation for enumerate.
If you need more information on enumerate, you can look up PEP 279 -- The enumerate() built-in function.
链接地址: http://www.djcxy.com/p/24008.html上一篇: 找到项目的位置在for循环一个序列