标签归档:loops

在Python中以相反顺序遍历列表

问题:在Python中以相反顺序遍历列表

所以我可以从开始到len(collection)结束collection[0]

我还希望能够访问循环索引。

So I can start from len(collection) and end in collection[0].

I also want to be able to access the loop index.


回答 0

使用内置reversed()功能:

>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
...     print(i)
... 
baz
bar
foo

要同时访问原始索引,请enumerate()在列表上使用,然后将其传递给reversed()

>>> for i, e in reversed(list(enumerate(a))):
...     print(i, e)
... 
2 baz
1 bar
0 foo

由于enumerate()返回生成器并且生成器不能反转,因此需要将其转换为list第一个。

Use the built-in reversed() function:

>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
...     print(i)
... 
baz
bar
foo

To also access the original index, use enumerate() on your list before passing it to reversed():

>>> for i, e in reversed(list(enumerate(a))):
...     print(i, e)
... 
2 baz
1 bar
0 foo

Since enumerate() returns a generator and generators can’t be reversed, you need to convert it to a list first.


回答 1

你可以做:

for item in my_list[::-1]:
    print item

(或者您想要在for循环中执行的任何操作。)

[::-1]切片反转for循环在列表中(但不会实际修改列表的“永久”)。

You can do:

for item in my_list[::-1]:
    print item

(Or whatever you want to do in the for loop.)

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

回答 3

可以这样完成:

对于范围(len(collect)-1,-1,-1)中的i:
    印刷品收藏[i]

    #为python 3打印(collection [i])。

因此,您的猜测非常接近:)有点尴尬,但这基本上是在说:从小于1开始len(collection),一直走到-1之前,以-1为步长。

Fyi,该help功能非常有用,因为它使您可以从Python控制台查看文档,例如:

help(range)

It can be done like this:

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:

help(range)


回答 4

reversed内置功能非常方便:

for item in reversed(sequence):

文档的反向解释它的局限性。

对于必须与索引一起反向遍历序列的情况(例如,对于更改序列长度的就地修改),我需要将此函数定义为我的codeutil模块:

import itertools
def reversed_enumerate(sequence):
    return itertools.izip(
        reversed(xrange(len(sequence))),
        reversed(sequence),
    )

这避免了创建序列的副本。显然,这些reversed限制仍然适用。

The reversed builtin function is handy:

for item in reversed(sequence):

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:

import itertools
def reversed_enumerate(sequence):
    return itertools.izip(
        reversed(xrange(len(sequence))),
        reversed(sequence),
    )

This one avoids creating a copy of the sequence. Obviously, the reversed limitations still apply.


回答 5

无需重新创建新列表,可以通过建立索引来实现:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

要么

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>

How about without recreating a new list, you can do by indexing:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

OR

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>

回答 6

>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

要么

>>> print l[::-1]
['d', 'c', 'b', 'a']
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

OR

>>> print l[::-1]
['d', 'c', 'b', 'a']

回答 7

我喜欢单线生成器方法:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))

I like the one-liner generator approach:

((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 > 0

for 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

回答 9

list.reverse()照常使用,然后进行迭代。

http://docs.python.org/tutorial/datastructures.html

Use list.reverse() and then iterate as you normally would.

http://docs.python.org/tutorial/datastructures.html


回答 10

没有导入的方法:

for i in range(1,len(arr)+1):
    print(arr[-i])

要么

for i in arr[::-1]:
    print(i)

An approach with no imports:

for i in range(1,len(arr)+1):
    print(arr[-i])

or

for i in arr[::-1]:
    print(i)

回答 11

def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)
def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)

回答 12

对于有什么价值的事情,您也可以这样做。很简单。

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]

for what ever it’s worth you can do it like this too. very simple.

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]

回答 13

reverse(enumerate(collection))在python 3中实现的一种表达方式:

zip(reversed(range(len(collection))), reversed(collection))

在python 2:

izip(reversed(xrange(len(collection))), reversed(collection))

我不确定为什么我们没有快捷方式,例如:

def reversed_enumerate(collection):
    return zip(reversed(range(len(collection))), reversed(collection))

还是为什么我们没有 reversed_range()

An expressive way to achieve reverse(enumerate(collection)) in python 3:

zip(reversed(range(len(collection))), reversed(collection))

in python 2:

izip(reversed(xrange(len(collection))), reversed(collection))

I’m not sure why we don’t have a shorthand for this, eg.:

def reversed_enumerate(collection):
    return zip(reversed(range(len(collection))), reversed(collection))

or why we don’t have reversed_range()


回答 14

如果您需要索引并且列表很小,那么最容易理解的方法是reversed(list(enumerate(your_list)))按照接受的答案进行操作。但这会创建列表的副本,因此,如果列表占用了很大一部分内存,则必须减去enumerate(reversed())从中返回的索引len()-1

如果您只需要执行一次:

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

the reverse function comes in handy here:

myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
    print x

回答 16

您还可以使用while循环:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1

You can also use a while loop:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1

回答 17

您可以在普通的for循环中使用负索引:

>>> collection = ["ham", "spam", "eggs", "baked beans"]
>>> for i in range(1, len(collection) + 1):
...     print(collection[-i])
... 
baked beans
eggs
spam
ham

要访问索引,就好像您正在遍历集合的反向副本一样,请使用i - 1

>>> for i in range(1, len(collection) + 1):
...     print(i-1, collection[-i])
... 
0 baked beans
1 eggs
2 spam
3 ham

要访问原始的非反向索引,请使用len(collection) - i

>>> for i in range(1, len(collection) + 1):
...     print(len(collection)-i, collection[-i])
... 
3 baked beans
2 eggs
1 spam
0 ham

You can use a negative index in an ordinary for loop:

>>> collection = ["ham", "spam", "eggs", "baked beans"]
>>> for i in range(1, len(collection) + 1):
...     print(collection[-i])
... 
baked beans
eggs
spam
ham

To access the index as though you were iterating forward over a reversed copy of the collection, use i - 1:

>>> for i in range(1, len(collection) + 1):
...     print(i-1, collection[-i])
... 
0 baked beans
1 eggs
2 spam
3 ham

To access the original, un-reversed index, use len(collection) - i:

>>> for i in range(1, len(collection) + 1):
...     print(len(collection)-i, collection[-i])
... 
3 baked beans
2 eggs
1 spam
0 ham

回答 18

如果您不介意索引为负,则可以执行以下操作:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

If you don’t mind the index being negative, you can do:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

回答 19

我认为最优雅的方法是转换enumeratereversed使用以下生成器

(-(ri+1), val) for ri, val in enumerate(reversed(foo))

生成enumerate迭代器的逆向

例:

foo = [1,2,3]
bar = [3,6,9]
[
    bar[i] - val
    for i, val in ((-(ri+1), val) for ri, val in enumerate(reversed(foo)))
]

结果:

[6, 4, 2]

I think the most elegant way is to transform enumerate and reversed using the following generator

(-(ri+1), val) for ri, val in enumerate(reversed(foo))

which generates a the reverse of the enumerate iterator

Example:

foo = [1,2,3]
bar = [3,6,9]
[
    bar[i] - val
    for i, val in ((-(ri+1), val) for ri, val in enumerate(reversed(foo)))
]

Result:

[6, 4, 2]

回答 20

其他答案是好的,但是如果您要作为 列表理解样式

collection = ['a','b','c']
[item for item in reversed( collection ) ]

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

回答 21

要使用负索引,请执行以下操作:从-1开始,然后在每次迭代后退-1。

>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
...     print i, a[i]
... 
-1 baz
-2 bar
-3 foo

To use negative indices: start at -1 and step back by -1 at each iteration.

>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
...     print i, a[i]
... 
-1 baz
-2 bar
-3 foo

回答 22

一个简单的方法:

n = int(input())
arr = list(map(int, input().split()))

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

A simple way :

n = int(input())
arr = list(map(int, input().split()))

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

回答 23

input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
    print(input_list[i])

我认为这也是一种简单的方法…从末尾读取并不断递减直到列表的长度,因为我们从不执行“ end”索引,因此也添加了-1

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

因此,最丑陋的选择xrange(len(xs)-1,-1,-1)是最快的。

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))

最后:

for i in gen:
    print(li[i])

希望对您有帮助。

you can use a generator:

li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))

finally:

for i in gen:
    print(li[i])

hope this help you.


访问“ for”循环中的索引?

问题:访问“ for”循环中的索引?

如何for在如下所示的循环中访问索引?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))

我想得到以下输出:

item #1 = 8
item #2 = 23
item #3 = 45
item #4 = 12
item #5 = 78

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

How do I access the index in a for loop like the following?

ints = [8, 23, 45, 12, 78]
for i in ints:
    print('item #{} = {}'.format(???, i))

I want to get this output:

item #1 = 8
item #2 = 23
item #3 = 45
item #4 = 12
item #5 = 78

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


回答 0

使用其他状态变量,例如索引变量(通常在C或PHP等语言中使用),被认为是非Python的。

更好的选择是使用enumerate()Python 2和3中都提供的内置函数。

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

进一步了解PEP 279

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:

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

Check out PEP 279 for more.


回答 1

使用for循环,在这种情况下如何访问循环索引(从1到5)?

用于enumerate在迭代时获取带有元素的索引:

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

并请注意,Python的索引从零开始,因此上述值将为0到4。如果要计数1到5,请执行以下操作:

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

单项控制流

您所要求的是以下Pythonic等效项,这是大多数低级语言程序员将使用的算法:

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

或使用没有for-each循环的语言:

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

或有时在Python中更常见(但唯一):

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

使用枚举功能

Python的enumerate功能通过隐藏索引的记帐,并将可迭代项封装到另一个可迭代项(一个enumerate对象)中,从而减少了视觉混乱,该可迭代项产生了两个索引元组以及原始可迭代项将提供的项目。看起来像这样:

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

此代码示例很好说明了Python特有的代码与非Python特有的代码之间的区别的典范示例。惯用代码是复杂的(但不复杂)Python,以预期使用的方式编写。语言的设计者期望使用惯用代码,这意味着通常该代码不仅更具可读性,而且效率更高。

计数

即使您不需要索引,但是您需要对迭代次数(有时是理想的)1进行计数,而最终的数字将是您的计数。

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

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

当您说想要从1到5时,该计数似乎更多地是您想要的内容(而不是索引)。


分解-逐步说明

为了分解这些示例,假设我们有一个要迭代的项目列表,并带有一个索引:

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

现在,我们通过此可迭代的枚举,创建一个枚举对象:

enumerate_object = enumerate(items) # the enumerate object

我们可以从该迭代中提取第一个项目,以使我们可以使用该next函数进行循环:

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

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

(0, 'a')

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

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

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

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

结论

  • Python索引从零开始
  • 要在迭代过程中从迭代器获取这些索引,请使用枚举函数
  • 以惯用方式使用枚举(以及元组拆包)将创建更易读和可维护的代码:

这样做:

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

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:

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'.

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

Conclusion

  • Python indexes start at zero
  • 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:

So do this:

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

回答 2

这是很简单的,从开始它1以外0

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

注意

重要提示,尽管index可能会引起误解,但tuple (idx, item)在这里。好去。

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

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

Note

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


回答 3

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

回答 4

按照Python的规范,有几种方法可以做到这一点。在所有示例中均假定:lst = [1, 2, 3, 4, 5]

1.使用枚举(被认为是最惯用的

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

我认为这也是最安全的选择,因为消除了进行无限递归的机会。项目及其索引都保存在变量中,无需编写任何其他代码即可访问该项目。

2.创建一个变量来保存索引(使用for

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

3.创建一个变量来保存索引(使用while

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

4.总有另一种方法

如前所述,还有其他方法尚未在此处进行说明,它们甚至可能在其他情况下更适用。例如使用itertools.chainfor。它比其他示例更好地处理嵌套循环。

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]
... 
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)
>>> 

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)
>>> 

回答 6

Python 2.7中访问循环内列表索引的最快方法是对小列表使用range方法,对中型和大型列表使用枚举方法

请参阅不同的方法,可以在列表和访问索引值被用来遍历和其性能指标(我想是对您有用)下面的代码样本:

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

请参阅以下每种方法的性能指标:

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

结果,使用range方法是列出1000个项目中最快的一种。对于大小大于10000的列表,enumerate则为获胜者。

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

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.

Adding some useful links below:


回答 7

首先,索引将从0到4。编程语言从0开始计数;从0开始计数。不要忘了,否则您将遇到索引超出范围的异常。for循环中需要的只是一个从0到4的变量,如下所示:

for x in range(0, 5):

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

要获取索引的值,请使用

list[index]

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)

结果:

# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)

for i, val in enumerate(items): print(i, val)

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

for i, val in enumerate(items):
    print("index", i, "for value", val)

结果:

# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78

for i, val in enumerate(items): print(i)

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

for i, val in enumerate(items):
    print("index", i)

结果:

# index 0
# index 1
# index 2
# index 3
# index 4

Here’s what you get when you’re accessing index in for loops:

for i in enumerate(items): print(i)

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

for i in enumerate(items):
    print("index/value", i)

Result:

# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)

for i, val in enumerate(items): print(i, val)

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

for i, val in enumerate(items):
    print("index", i, "for value", val)

Result:

# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78

for i, val in enumerate(items): print(i)

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

for i, val in enumerate(items):
    print("index", i)

Result:

# index 0
# index 1
# index 2
# index 3
# index 4

回答 9

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

循环计数器迭代

当前用于遍历索引的惯用法使用内置range函数:

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

可以通过旧习惯用法或使用新的zip内置函数来实现元素和索引的循环:

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

要么

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

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

According to this discussion: 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:

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/


回答 10

您可以使用以下代码进行操作:

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

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

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

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

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

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

回答 11

解决此问题的最佳方法是使用枚举内置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)

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)

回答 12

在您的问题中,您写道:“在这种情况下,我如何从1到5访问循环索引?”

但是,列表的索引从零开始。因此,那么我们需要知道您真正想要的是列表中每个项目的索引和项目,还是您真正想要的是从1开始的数字。幸运的是,在Python中,执行这一项或两项都很容易。

首先,要澄清一下,该enumerate函数迭代地返回列表中每个项目的索引和相应项目。

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

上面的输出是

0 1
1 2
2 3
3 4
4 5

请注意,索引从0开始。这种索引在包括Python和C在内的现代编程语言中很常见。

如果希望循环跨越列表的一部分,则可以将标准Python语法用于列表的一部分。例如,要从列表中的第二个项目循环到最后一个但不包括最后一个项目,可以使用

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

请再次注意,输出索引从0开始,

0 2
1 3
2 4

这给我们带来了start=n的开关enumerate()。这只是使索引偏移,您可以等效地在循环内向索引简单地添加一个数字。

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

其输出是

1 1
2 2
3 3
4 4
5 5

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)

或获得长度为 l = len(nums)

for i in range(l):
    print(i+1, nums[i])

If I were to iterate nums = [1, 2, 3, 4, 5] I would do

for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)

for i in range(l):
    print(i+1, nums[i])

回答 14

如果列表中没有重复的值:

for i in ints:
    indx = ints.index(i)
    print(i, indx)

If there is no duplicate value in the list:

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)

输出是

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

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']

回答 16

您可以使用index方法

ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]

编辑 在注释中突出显示,如果中存在重复项ints,则此方法不起作用,下面的方法应适用于以下任何值ints

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]

或者

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]

如果要同时获取索引和值ints作为元组列表。

它使用在enumerate此问题的选定答案中的方法,但具有列表理解功能,因此可以用较少的代码来加快速度。

You can use the index method

ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]

EDIT Highlighted in the comment that this method doesn’t work if there are duplicates in ints, the method below should work for any values in ints:

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]

Or alternatively

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]

if you want to get both the index and the value in ints as a list of tuples.

It uses the method of enumerate in the selected answer to this question, but with list comprehension, making it faster with less code.


回答 17

使用While循环的简单答案:

arr = [8, 23, 45, 12, 78]
i = 0
while i<len(arr):
    print("Item ",i+1," = ",arr[i])
    i +=1

输出:

Simple answer using While Loop:

arr = [8, 23, 45, 12, 78]
i = 0
while i<len(arr):
    print("Item ",i+1," = ",arr[i])
    i +=1

Output:


回答 18

要使用for循环在列表理解中打印(索引,值)的元组:

ints = [8, 23, 45, 12, 78]
print [(i,ints[i]) for i in range(len(ints))]

输出:

[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

To print tuple of (index, value) in list comprehension using a for loop:

ints = [8, 23, 45, 12, 78]
print [(i,ints[i]) for i in range(len(ints))]

Output:

[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

回答 19

这足以达到目的:

list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)

This serves the purpose well enough:

list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)