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:24
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.

查看更多
骚的不知所云
3楼-- · 2018-12-31 01:25
for i in range(len(ints)):
   print i, ints[i]
查看更多
人间绝色
4楼-- · 2018-12-31 01:28

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)
查看更多
骚的不知所云
5楼-- · 2018-12-31 01:28

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.

查看更多
登录 后发表回答