在Python中使用"for"计算索引

Luc*_*nde 43 python indexing for-loop count

我需要在Python中做同样的事情:

for (i = 0; i < 5; i++) {cout << i;} 
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在Python中使用FOR来获取列表中元素的索引.

Sve*_*ach 73

如果您有一些给定的列表,并希望迭代其项目索引,您可以使用enumerate():

for index, item in enumerate(my_list):
    print index, item
Run Code Online (Sandbox Code Playgroud)

如果您只需要索引,则可以使用range():

for i in range(len(my_list)):
    print i
Run Code Online (Sandbox Code Playgroud)


dan*_*007 21

只是用

for i in range(0, 5):
    print i
Run Code Online (Sandbox Code Playgroud)

迭代您的数据集并打印每个值.

对于大型数据集,您希望使用xrange,它具有非常相似的签名,但对于较大的数据集更有效.http://docs.python.org/library/functions.html#xrange


pki*_*kit 14

如果您有一个现有列表,并且想要循环它并跟踪索引,则可以使用该enumerate函数.例如

l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
   print "index", i, "is", fruit
Run Code Online (Sandbox Code Playgroud)


bgp*_*ter 8

使用枚举:

>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
...    print "%d: %s" % (index, val)
... 
0: a
1: b
2: c
3: d
Run Code Online (Sandbox Code Playgroud)