The [::-1] slice reverses the list in the for loop (but won’t actually modify your list “permanently”).
回答 2
如果您需要循环索引,并且不想遍历整个列表两次,或者不想使用额外的内存,则可以编写一个生成器。
def reverse_enum(L):for index in reversed(xrange(len(L))):yield index, L[index]
L =['foo','bar','bas']for index, item in reverse_enum(L):print index, item
If you need the loop index, and don’t want to traverse the entire list twice, or use extra memory, I’d write a generator.
def reverse_enum(L):
for index in reversed(xrange(len(L))):
yield index, L[index]
L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
print index, item
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
So your guess was pretty close :) A little awkward but it’s basically saying: start with 1 less than len(collection), keep going until you get to just before -1, by steps of -1.
Fyi, the help function is very useful as it lets you view the docs for something from the Python console, eg:
The documentation for reversed explains its limitations.
For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))
回答 8
另外,您可以使用“范围”或“计数”功能。如下:
a =["foo","bar","baz"]for i in range(len(a)-1,-1,-1):print(i, a[i])3 baz
2 bar
1 foo
您还可以按以下方式使用itertools中的“ count”:
a =["foo","bar","baz"]from itertools import count, takewhile
def larger_than_0(x):return x >0for x in takewhile(larger_than_0, count(3,-1)):print(x, a[x-1])3 baz
2 bar
1 foo
Also, you could use either “range” or “count” functions.
As follows:
a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
print(i, a[i])
3 baz
2 bar
1 foo
You could also use “count” from itertools as following:
a = ["foo", "bar", "baz"]
from itertools import count, takewhile
def larger_than_0(x):
return x > 0
for x in takewhile(larger_than_0, count(3, -1)):
print(x, a[x-1])
3 baz
2 bar
1 foo
a =['b','d','c','a']for index, value in enumerate(reversed(a)):
index = len(a)-1- index
do_something(index, value)
或者,如果您需要多次执行此操作,则应使用生成器:
def enumerate_reversed(lyst):for index, value in enumerate(reversed(lyst)):
index = len(lyst)-1- index
yield index, value
for index, value in enumerate_reversed(a):
do_something(index, value)
If you need the index and your list is small, the most readable way is to do reversed(list(enumerate(your_list))) like the accepted answer says. But this creates a copy of your list, so if your list is taking up a large portion of your memory you’ll have to subtract the index returned by enumerate(reversed()) from len()-1.
If you just need to do it once:
a = ['b', 'd', 'c', 'a']
for index, value in enumerate(reversed(a)):
index = len(a)-1 - index
do_something(index, value)
or if you need to do this multiple times you should use a generator:
def enumerate_reversed(lyst):
for index, value in enumerate(reversed(lyst)):
index = len(lyst)-1 - index
yield index, value
for index, value in enumerate_reversed(a):
do_something(index, value)
回答 15
反向功能在这里很方便:
myArray =[1,2,3,4]
myArray.reverse()for x in myArray:print x
input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
print(input_list[i])
i think this one is also simple way to do it… read from end and keep decrementing till the length of list, since we never execute the “end” index hence added -1 also
回答 24
假设任务是在列表中找到满足某些条件的最后一个元素(即向后看时的第一个元素),我得到以下数字:
>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))4.6937971115112305>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))4.809093952178955>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))4.931743860244751>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))5.548468112945557>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))6.286104917526245>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n i -= 1\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))8.384078979492188
Assuming task is to find last element that satisfies some condition in a list (i.e. first when looking backwards), I’m getting following numbers:
>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.6937971115112305
>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.809093952178955
>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
4.931743860244751
>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
5.548468112945557
>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))
6.286104917526245
>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n i -= 1\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
8.384078979492188
So, the ugliest option xrange(len(xs)-1,-1,-1) is the fastest.
回答 25
您可以使用生成器:
li =[1,2,3,4,5,6]
len_li = len(li)
gen =(len_li-1-i for i in range(len_li))
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)