在Python中的“ for”循环中访问索引

使用长度范围 (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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值