使用长度范围 (Using range of length)
Using the range function along with the len() on a list or any collection will give access to the index of each item in the collection. One such example is below,
在列表或任何集合上使用range函数和len()可以访问集合中每个项目的索引。 下面是一个这样的例子,
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list_of_cities = ['bangalore', 'delhi', 'mumbai', 'pune', 'chennai', 'vizag']
>>> for i in range(len(list_of_cities)):
... print("I like the city {}".format(list_of_cities[i]))
...
Output
输出量
I like the city bangalore
I like the city delhi
I like the city mumbai
I like the city pune
I like the city chennai
I like the city vizag
使用枚举 (Using enumerate)
Enumerate is also one such function that provides an option to read the index of the collection. Enumerate is a more idiomatic way to accomplish this task,
枚举也是这样一种功能,它提供了一个选项来读取集合的索引。 枚举是完成此任务的更惯用的方法,
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> list_of_cities = ['bangalore', 'delhi', 'mumbai', 'pune', 'chennai', 'vizag']
>>> for num, name in enumerate(list_of_cities, start =1):
... print( num, name)
...
Output
输出量
1 bangalore
2 delhi
3 mumbai
4 pune
5 chennai
6 vizag
Here in the above example, num refers to the index and name refers to the item in the given num index.
在上面的示例中, num是指索引,名称是指给定num索引中的项目。
翻译自: https://www.includehelp.com/python/accessing-the-index-in-for-loops-in-python.aspx