Accessing the index in 'for' loops?

2018-12-31 00:26发布

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?

22条回答
还给你的自由
2楼-- · 2018-12-31 01:02

In you 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 known 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
查看更多
永恒的永恒
3楼-- · 2018-12-31 01:05

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.

查看更多
公子世无双
4楼-- · 2018-12-31 01:06

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)]
查看更多
牵手、夕阳
5楼-- · 2018-12-31 01:07

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']
查看更多
不再属于我。
6楼-- · 2018-12-31 01:08

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.

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 01:08

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[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/

查看更多
登录 后发表回答