使用Python“for”循环访问索引。

时间:2023-01-06 00:08:08

How do I access the index itself for a list like the following?

我如何访问该索引本身,以获得如下所示的列表?

ints = [8, 23, 45, 12, 78]

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

当我使用for循环遍历它时,在这种情况下,如何访问循环索引,从1到5 ?

15 个解决方案

#1


4107  

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

使用一个额外的状态变量,比如索引变量(通常用在C或PHP之类的语言中),被认为是非python的。

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

更好的选择是使用内置函数枚举(),在Python 2和3中都可以使用:

for idx, val in enumerate(ints):
    print(idx, val)

Check out PEP 279 for more.

查看PEP 279,了解更多信息。

#2


436  

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

在迭代时使用枚举来获得元素的索引:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

请注意,Python的索引从0开始,因此您将得到上面的0到4。如果你想要计数,1到5,做这个:

for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

你所要求的是python的以下内容,这是大多数低级语言程序员使用的算法:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

或者在没有for-each循环的语言中:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

或者是在Python中发现的更常见的(但不统一的):

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

Python的枚举函数通过隐藏索引的方法来减少视觉上的混乱,并将iterable封装到另一个可迭代的(枚举对象)中,从而生成索引的两项元组和原始iterable所提供的项。像这样:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

这段代码示例很好地说明了代码之间的区别,这是Python的惯用代码,而代码则不是。惯用代码是复杂的(但不是复杂的)Python,它的编写方式是要使用的。语言的设计者期望使用惯用代码,这意味着通常这段代码不仅可读性更好,而且更有效。

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

即使您不需要索引,但是您需要一个迭代的计数(有时是可取的),您可以从1开始,最后的数字将是您的计数。

for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.

当你说你想要从1到5的时候,计数似乎是你想要的(而不是指数)。


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

为了打破这些例子,假设我们有一个项目列表,我们想要迭代一个索引:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

现在我们通过这个iterable枚举,创建一个枚举对象:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

我们可以把第一个项从这个迭代中拉出来我们会得到一个循环下一个函数:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

我们看到我们得到了一个0的元组,第一个索引,和'a',第一项:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

我们可以使用所谓的“序列解包”来提取这两元组中的元素:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

当我们检查索引时,我们发现它指的是第一个索引,0,item指的是第一项,'a'。

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • Python索引从0开始。
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • 要从迭代中获得这些索引,请使用枚举函数。
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:
  • 在惯用方法中使用枚举(以及tuple unpacking)创建更易于阅读和可维护的代码:

So do this:

所以这样做:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)

#3


96  

It's pretty simple to start it from 1 other than 0:

从0开始,很简单:

for index in enumerate(iterable, start=1):
   print index

Note

Important hint, though a little misleading, since index will be a tuple (idx, item) here. Good to go.

重要提示,尽管有点误导,因为索引将是一个元组(idx,项)。好了。

#4


60  

for i in range(len(ints)):
   print i, ints[i]

#5


27  

As is the norm in Python there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

正如Python中的规范一样,有几种方法可以做到这一点。在所有的例子中假设:lst = [1,2,3,4,5]

1. Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

在我看来,这也是最安全的选择,因为进入无限递归的机会已经被消除了。项目及其索引都保存在变量中,不需要再编写任何代码来访问该项目。

2. Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

3. Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # you will have to write extra code to get the element
    index += 1  # escape infinite recursion

4. There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using itertools.chain with for. It handles nested loops better than the other examples.

如前所述,还有其他方法可以做到这一点,在这里没有解释,甚至在其他情况下也可以应用更多。e。g出现使用itertools。链的。它比其他示例更好地处理嵌套循环。

#6


15  

Old fashioned way:

老式的方法:

for ix in range(len(ints)):
    print ints[ix]

List comprehension:

列表理解:

[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
... 
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print tup
... 
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>> 

#7


12  

ints = [9, 23, 45, 12, 78]
ints.extend([1,2,3,4,5,6,7,8])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can extend a list. Extend means you can add multiple values at a time.

这样可以扩展列表。扩展意味着您可以一次添加多个值。

To append this list you have to write the code given below:

要追加这个列表,你必须写下面的代码:

ints = [9, 23, 45, 12, 78]
ints.append([1])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can add a single value at a time. If you write ints.append([1]) so this will create a sub list for this element.

这样,您可以一次添加一个值。如果您写入ints.append([1]),那么这将为该元素创建一个子列表。

#8


12  

The fastest way to access indexes of list within loop in Python 2.7 is to use the range method for small lists and enumerate method for medium and huge size lists.

在Python 2.7中,访问循环中列表索引的最快方法是使用小列表的范围方法和枚举中和大型列表的方法。

Please see different approaches which can be used to iterate over list and access index value and their performance metrics (which I suppose would be useful for you) in code samples below:

请查看不同的方法,这些方法可用于迭代列表和访问索引值及其性能指标(我认为这对您有用):

from timeit import timeit

# Using range
def range_loop(iterable):
    for i in range(len(iterable)):
        1 + iterable[i]

# Using xrange
def xrange_loop(iterable):
    for i in xrange(len(iterable)):
        1 + iterable[i]

# Using enumerate
def enumerate_loop(iterable):
    for i, val in enumerate(iterable):
        1 + val

# Manual indexing
def manual_indexing_loop(iterable):
    index = 0
    for item in iterable:
        1 + item
        index += 1

See performance metrics for each method below:

参见下面每个方法的性能指标:

from timeit import timeit

def measure(l, number=10000):
print "Measure speed for list with %d items" % len(l)
print "xrange: ", timeit(lambda :xrange_loop(l), number=number)
print "range: ", timeit(lambda :range_loop(l), number=number)
print "enumerate: ", timeit(lambda :enumerate_loop(l), number=number)
print "manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number)

measure(range(1000))
# Measure speed for list with 1000 items
# xrange:  0.758321046829
# range:  0.701184988022
# enumerate:  0.724966049194
# manual_indexing:  0.894635915756

measure(range(10000))
# Measure speed for list with 100000 items
# xrange:  81.4756360054
# range:  75.0172479153
# enumerate:  74.687623024
# manual_indexing:  91.6308541298

measure(range(10000000), number=100)
# Measure speed for list with 10000000 items
# xrange:  82.267786026
# range:  84.0493988991
# enumerate:  78.0344707966
# manual_indexing:  95.0491430759

As the result, using range method is the fastest one up to list with 1000 items. For list with size > 10 000 items enumerate is the winner.

因此,使用range方法是最快列出1000个条目的方法。清单中有大小>万项的项目不胜枚举。

Adding some useful links below:

在下面添加一些有用的链接:

#9


12  

I don't know if the following is pythonic or not, but it uses the Python function enumerate and prints the index and the value.

我不知道下面是不是Python,但是它使用Python函数枚举和打印索引和值。

int_list = [8, 23, 45, 12, 78]
for index, value in enumerate(int_list):
   print(index, value)

Output:

输出:

0 8
1 23
2 45
3 12
4 78

#10


10  

First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:

首先,索引从0到4。编程语言从0开始计数;别忘了,否则你会遇到一个异常的索引。for循环中所需要的是一个从0到4的变量,例如:

for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)

请记住,我将0写到5,因为循环在max之前停止了一个数字。:)

To get the value of an index use

以获得索引使用的值。

list[index]

#11


8  

According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index

根据这个讨论:http://bytes.com/topic/python/answers/464012-objects-list-index。

Loop counter iteration

循环计数器迭代

The current idiom for looping over the indices makes use of the built-in 'range' function:

当前用于循环索引的习惯用法是使用内置的“范围”函数:

for i in range(len(sequence)):
    # work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:

通过使用旧的习惯用法或使用新的“zip”内置函数,可以实现对两个元素和索引的循环[2]:

for i in range(len(sequence)):
    e = sequence[i]
    # work with index i and element e

or

for i, e in zip(range(len(sequence)), sequence):
    # work with index i and element e

via http://www.python.org/dev/peps/pep-0212/

通过http://www.python.org/dev/peps/pep-0212/

#12


8  

You can do it with this code:

你可以用下面的代码来做:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:

如果需要在循环结束时重置索引值,请使用此代码:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

#13


7  

Best solution for this problem is use enumerate in-build python function.
enumerate return tuple
first value is index
second value is element of array at that index

这个问题的最佳解决方案是使用枚举的in-build python函数。枚举返回元组的第一个值是索引第二个值是该索引中的数组元素。

In [1]: ints = [8, 23, 45, 12, 78]

In [2]: for idx, val in enumerate(ints):
   ...:         print(idx, val)
   ...:     
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)

#14


3  

You can also try this:

你也可以试试:

data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
      a = (i, str(item).split('.'))
      x.append(a)
for index, value in x:
     print(index, value)

The output is

输出是

0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']

#15


0  

You've received a number of answers explaining enumerate, but if you only need the index for accessing matching entries in two lists, there's another way that's cleaner and simpler in Python 3: zip.

您已经收到了许多解释枚举的答案,但是如果您只需要在两个列表中访问匹配项的索引,那么在Python 3中有另一种更简洁更简单的方法:zip。

For example, if you're using the index to pull out corresponding names for the numbers in your list, you could do it like this:

例如,如果您使用索引为列表中的数字提取相应的名称,您可以这样做:

ints = [8, 23, 45, 12, 78]
names = ["John", "Sue", "Johannes", "Patel", "Ian"]
for int, name = zip(ints, names):
    print("{} - {}".format(name, int)

That would produce

这将产生

8 - John
23 - Sue
45 - Johannes
12 - Patel
78 - Ian

#1


4107  

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

使用一个额外的状态变量,比如索引变量(通常用在C或PHP之类的语言中),被认为是非python的。

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

更好的选择是使用内置函数枚举(),在Python 2和3中都可以使用:

for idx, val in enumerate(ints):
    print(idx, val)

Check out PEP 279 for more.

查看PEP 279,了解更多信息。

#2


436  

Using a for loop, how do I access the loop index, from 1 to 5 in this case?

Use enumerate to get the index with the element as you iterate:

在迭代时使用枚举来获得元素的索引:

for index, item in enumerate(items):
    print(index, item)

And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:

请注意,Python的索引从0开始,因此您将得到上面的0到4。如果你想要计数,1到5,做这个:

for count, item in enumerate(items, start=1):
    print(count, item)

Unidiomatic control flow

What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:

你所要求的是python的以下内容,这是大多数低级语言程序员使用的算法:

index = 0            # Python's indexing starts at zero
for item in items:   # Python's for loops are a "for each" loop 
    print(index, item)
    index += 1

Or in languages that do not have a for-each loop:

或者在没有for-each循环的语言中:

index = 0
while index < len(items):
    print(index, items[index])
    index += 1

or sometimes more commonly (but unidiomatically) found in Python:

或者是在Python中发现的更常见的(但不统一的):

for index in range(len(items)):
    print(index, items[index])

Use the Enumerate Function

Python's enumerate function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:

Python的枚举函数通过隐藏索引的方法来减少视觉上的混乱,并将iterable封装到另一个可迭代的(枚举对象)中,从而生成索引的两项元组和原始iterable所提供的项。像这样:

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.

这段代码示例很好地说明了代码之间的区别,这是Python的惯用代码,而代码则不是。惯用代码是复杂的(但不是复杂的)Python,它的编写方式是要使用的。语言的设计者期望使用惯用代码,这意味着通常这段代码不仅可读性更好,而且更有效。

Getting a count

Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1 and the final number will be your count.

即使您不需要索引,但是您需要一个迭代的计数(有时是可取的),您可以从1开始,最后的数字将是您的计数。

for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))

The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.

当你说你想要从1到5的时候,计数似乎是你想要的(而不是指数)。


Breaking it down - a step by step explanation

To break these examples down, say we have a list of items that we want to iterate over with an index:

为了打破这些例子,假设我们有一个项目列表,我们想要迭代一个索引:

items = ['a', 'b', 'c', 'd', 'e']

Now we pass this iterable to enumerate, creating an enumerate object:

现在我们通过这个iterable枚举,创建一个枚举对象:

enumerate_object = enumerate(items) # the enumerate object

We can pull the first item out of this iterable that we would get in a loop with the next function:

我们可以把第一个项从这个迭代中拉出来我们会得到一个循环下一个函数:

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

And we see we get a tuple of 0, the first index, and 'a', the first item:

我们看到我们得到了一个0的元组,第一个索引,和'a',第一项:

(0, 'a')

we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:

我们可以使用所谓的“序列解包”来提取这两元组中的元素:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

and when we inspect index, we find it refers to the first index, 0, and item refers to the first item, 'a'.

当我们检查索引时,我们发现它指的是第一个索引,0,item指的是第一项,'a'。

>>> print(index)
0
>>> print(item)
a

Conclusion

  • Python indexes start at zero
  • Python索引从0开始。
  • To get these indexes from an iterable as you iterate over it, use the enumerate function
  • 要从迭代中获得这些索引,请使用枚举函数。
  • Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:
  • 在惯用方法中使用枚举(以及tuple unpacking)创建更易于阅读和可维护的代码:

So do this:

所以这样做:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)

#3


96  

It's pretty simple to start it from 1 other than 0:

从0开始,很简单:

for index in enumerate(iterable, start=1):
   print index

Note

Important hint, though a little misleading, since index will be a tuple (idx, item) here. Good to go.

重要提示,尽管有点误导,因为索引将是一个元组(idx,项)。好了。

#4


60  

for i in range(len(ints)):
   print i, ints[i]

#5


27  

As is the norm in Python there are several ways to do this. In all examples assume: lst = [1, 2, 3, 4, 5]

正如Python中的规范一样,有几种方法可以做到这一点。在所有的例子中假设:lst = [1,2,3,4,5]

1. Using enumerate (considered most idiomatic)

for index, element in enumerate(lst):
    # do the things that need doing here

This is also the safest option in my opinion because the chance of going into infinite recursion has been eliminated. Both the item and its index are held in variables and there is no need to write any further code to access the item.

在我看来,这也是最安全的选择,因为进入无限递归的机会已经被消除了。项目及其索引都保存在变量中,不需要再编写任何代码来访问该项目。

2. Creating a variable to hold the index (using for)

for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

3. Creating a variable to hold the index (using while)

index = 0
while index < len(lst):
    # you will have to write extra code to get the element
    index += 1  # escape infinite recursion

4. There is always another way

As explained before, there are other ways to do this that have not been explained here and they may even apply more in other situations. e.g using itertools.chain with for. It handles nested loops better than the other examples.

如前所述,还有其他方法可以做到这一点,在这里没有解释,甚至在其他情况下也可以应用更多。e。g出现使用itertools。链的。它比其他示例更好地处理嵌套循环。

#6


15  

Old fashioned way:

老式的方法:

for ix in range(len(ints)):
    print ints[ix]

List comprehension:

列表理解:

[ (ix, ints[ix]) for ix in range(len(ints))]

>>> ints
[1, 2, 3, 4, 5]
>>> for ix in range(len(ints)): print ints[ix]
... 
1
2
3
4
5
>>> [ (ix, ints[ix]) for ix in range(len(ints))]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
>>> lc = [ (ix, ints[ix]) for ix in range(len(ints))]
>>> for tup in lc:
...     print tup
... 
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
>>> 

#7


12  

ints = [9, 23, 45, 12, 78]
ints.extend([1,2,3,4,5,6,7,8])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can extend a list. Extend means you can add multiple values at a time.

这样可以扩展列表。扩展意味着您可以一次添加多个值。

To append this list you have to write the code given below:

要追加这个列表,你必须写下面的代码:

ints = [9, 23, 45, 12, 78]
ints.append([1])
for idx, val in enumerate(ints):
    print(idx,val)

This way you can add a single value at a time. If you write ints.append([1]) so this will create a sub list for this element.

这样,您可以一次添加一个值。如果您写入ints.append([1]),那么这将为该元素创建一个子列表。

#8


12  

The fastest way to access indexes of list within loop in Python 2.7 is to use the range method for small lists and enumerate method for medium and huge size lists.

在Python 2.7中,访问循环中列表索引的最快方法是使用小列表的范围方法和枚举中和大型列表的方法。

Please see different approaches which can be used to iterate over list and access index value and their performance metrics (which I suppose would be useful for you) in code samples below:

请查看不同的方法,这些方法可用于迭代列表和访问索引值及其性能指标(我认为这对您有用):

from timeit import timeit

# Using range
def range_loop(iterable):
    for i in range(len(iterable)):
        1 + iterable[i]

# Using xrange
def xrange_loop(iterable):
    for i in xrange(len(iterable)):
        1 + iterable[i]

# Using enumerate
def enumerate_loop(iterable):
    for i, val in enumerate(iterable):
        1 + val

# Manual indexing
def manual_indexing_loop(iterable):
    index = 0
    for item in iterable:
        1 + item
        index += 1

See performance metrics for each method below:

参见下面每个方法的性能指标:

from timeit import timeit

def measure(l, number=10000):
print "Measure speed for list with %d items" % len(l)
print "xrange: ", timeit(lambda :xrange_loop(l), number=number)
print "range: ", timeit(lambda :range_loop(l), number=number)
print "enumerate: ", timeit(lambda :enumerate_loop(l), number=number)
print "manual_indexing: ", timeit(lambda :manual_indexing_loop(l), number=number)

measure(range(1000))
# Measure speed for list with 1000 items
# xrange:  0.758321046829
# range:  0.701184988022
# enumerate:  0.724966049194
# manual_indexing:  0.894635915756

measure(range(10000))
# Measure speed for list with 100000 items
# xrange:  81.4756360054
# range:  75.0172479153
# enumerate:  74.687623024
# manual_indexing:  91.6308541298

measure(range(10000000), number=100)
# Measure speed for list with 10000000 items
# xrange:  82.267786026
# range:  84.0493988991
# enumerate:  78.0344707966
# manual_indexing:  95.0491430759

As the result, using range method is the fastest one up to list with 1000 items. For list with size > 10 000 items enumerate is the winner.

因此,使用range方法是最快列出1000个条目的方法。清单中有大小>万项的项目不胜枚举。

Adding some useful links below:

在下面添加一些有用的链接:

#9


12  

I don't know if the following is pythonic or not, but it uses the Python function enumerate and prints the index and the value.

我不知道下面是不是Python,但是它使用Python函数枚举和打印索引和值。

int_list = [8, 23, 45, 12, 78]
for index, value in enumerate(int_list):
   print(index, value)

Output:

输出:

0 8
1 23
2 45
3 12
4 78

#10


10  

First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:

首先,索引从0到4。编程语言从0开始计数;别忘了,否则你会遇到一个异常的索引。for循环中所需要的是一个从0到4的变量,例如:

for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)

请记住,我将0写到5,因为循环在max之前停止了一个数字。:)

To get the value of an index use

以获得索引使用的值。

list[index]

#11


8  

According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index

根据这个讨论:http://bytes.com/topic/python/answers/464012-objects-list-index。

Loop counter iteration

循环计数器迭代

The current idiom for looping over the indices makes use of the built-in 'range' function:

当前用于循环索引的习惯用法是使用内置的“范围”函数:

for i in range(len(sequence)):
    # work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new 'zip' built-in function[2]:

通过使用旧的习惯用法或使用新的“zip”内置函数,可以实现对两个元素和索引的循环[2]:

for i in range(len(sequence)):
    e = sequence[i]
    # work with index i and element e

or

for i, e in zip(range(len(sequence)), sequence):
    # work with index i and element e

via http://www.python.org/dev/peps/pep-0212/

通过http://www.python.org/dev/peps/pep-0212/

#12


8  

You can do it with this code:

你可以用下面的代码来做:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:

如果需要在循环结束时重置索引值,请使用此代码:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

#13


7  

Best solution for this problem is use enumerate in-build python function.
enumerate return tuple
first value is index
second value is element of array at that index

这个问题的最佳解决方案是使用枚举的in-build python函数。枚举返回元组的第一个值是索引第二个值是该索引中的数组元素。

In [1]: ints = [8, 23, 45, 12, 78]

In [2]: for idx, val in enumerate(ints):
   ...:         print(idx, val)
   ...:     
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)

#14


3  

You can also try this:

你也可以试试:

data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
      a = (i, str(item).split('.'))
      x.append(a)
for index, value in x:
     print(index, value)

The output is

输出是

0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']

#15


0  

You've received a number of answers explaining enumerate, but if you only need the index for accessing matching entries in two lists, there's another way that's cleaner and simpler in Python 3: zip.

您已经收到了许多解释枚举的答案,但是如果您只需要在两个列表中访问匹配项的索引,那么在Python 3中有另一种更简洁更简单的方法:zip。

For example, if you're using the index to pull out corresponding names for the numbers in your list, you could do it like this:

例如,如果您使用索引为列表中的数字提取相应的名称,您可以这样做:

ints = [8, 23, 45, 12, 78]
names = ["John", "Sue", "Johannes", "Patel", "Ian"]
for int, name = zip(ints, names):
    print("{} - {}".format(name, int)

That would produce

这将产生

8 - John
23 - Sue
45 - Johannes
12 - Patel
78 - Ian