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.
The better option is to use the built-in function enumerate(), available in both Python 2 and 3:
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:
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:
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:
index = 0
while index < len(items):
print(index, items[index])
index += 1
or sometimes more commonly (but unidiomatically) found in 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:
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.
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.
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.
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:
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')
we can use what is referred to as “sequence unpacking” to extract the elements from this two-tuple:
As is the norm in Python there are several ways to do this. In all examples assume: 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.
回答 5
老式的方式:
for ix in range(len(ints)):print ints[ix]
清单理解:
[(ix, ints[ix])for ix in range(len(ints))]>>> ints
[1,2,3,4,5]>>>for ix in range(len(ints)):print ints[ix]...12345>>>[(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)>>>
from timeit import timeit
# Using rangedef range_loop(iterable):for i in range(len(iterable)):1+ iterable[i]# Using xrangedef xrange_loop(iterable):for i in xrange(len(iterable)):1+ iterable[i]# Using enumeratedef enumerate_loop(iterable):for i, val in enumerate(iterable):1+ val
# Manual indexingdef manual_indexing_loop(iterable):
index =0for item in iterable:1+ item
index +=1
请参阅以下每种方法的性能指标:
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
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.
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.
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:
for x in range(0, 5):
Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)
To get the value of an index use
list[index]
回答 8
这是for循环访问索引时得到的结果:
for i in enumerate(items): print(i)
items =[8,23,45,12,78]for i in enumerate(items):print("index/value", i)
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 [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)
In your question, you write “how do I access the loop index, from 1 to 5 in this case?”
However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.
First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.
alist = [1, 2, 3, 4, 5]
for n, a in enumerate(alist):
print("%d %d" % (n, a))
The output for the above is then,
0 1
1 2
2 3
3 4
4 5
Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.
If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use
for n, a in enumerate(alist[1:-1]):
print("%d %d" % (n, a))
Note that once again, the output index runs from 0,
0 2
1 3
2 4
That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.
for n, a in enumerate(alist, start=1):
print("%d %d" % (n, a))
for which the output is
1 1
2 2
3 3
4 4
5 5
回答 13
如果我要迭代,nums = [1, 2, 3, 4, 5]我会做
for i, num in enumerate(nums, start=1):print(i, num)
for i in ints:
indx = ints.index(i)
print(i, indx)
回答 15
您也可以尝试以下操作:
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)
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)