访问'for'循环中的索引

如何在使用for循环迭代序列时访问索引?

xs = [8, 23, 45]
for x in xs:print("item #{} = {}".format(index, x))

期望输出:

item #1 = 8item #2 = 23item #3 = 45
3592068 次浏览
for i in range(len(ints)):print(i, ints[i]) # print updated to print() in Python 3.x+

老式的方式:

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

使用内置函数#0

for idx, x in enumerate(xs):print(idx, x)

通过for i in range(len(xs)): x = xs[i]手动索引或手动管理附加状态变量是非pythonic

查看PEP 279了解更多。

根据这个讨论:对象的列表索引

循环计数器迭代

当前循环索引的习惯用法使用内置的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

通过PEP 212-循环计数器迭代

0以外的1开始很简单:

for index, item in enumerate(iterable, start=1):print index, item  # Used to print in python<3.xprint(index, item) # Migrate to print() after 3.x+   

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

在迭代时使用enumerate获取包含元素的索引:

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

请注意,Python的索引从零开始,因此上面的值将得到0到4。如果你想要1到5的计数,请这样做:

count = 0 # in case items is empty and you need it after the loopfor count, item in enumerate(items, start=1):print(count, item)

通用控制流

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

index = 0            # Python's indexing starts at zerofor item in items:   # Python's for loops are a "for each" loopprint(index, item)index += 1

或者在没有for-each循环的语言中:

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

或者有时在Python中更常见(但单调地):

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

使用枚举函数

Python的#0函数通过隐藏索引的核算,并将可迭代对象封装到另一个可迭代对象(enumerate对象)中来减少视觉混乱,该可迭代对象产生索引的两项元组和原始可迭代对象将提供的项。看起来像这样:

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

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

数一下

即使您不需要索引,但您需要迭代计数(有时需要),您可以从1开始,最终数字将是您的计数。

count = 0 # in case items is emptyfor count, item in enumerate(items, start=1):   # default is zeroprint(item)
print('there were {0} items printed'.format(count))

当您说您想要从1到5时,计数似乎更符合您的要求(而不是索引)。


打破它-一步一步的解释

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

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

现在我们将这个可迭代对象传递给enumerate,创建一个enumerate对象:

enumerate_object = enumerate(items) # the enumerate object

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

iteration = next(enumerate_object) # first iteration from enumerateprint(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索引从零开始
  • 要在迭代可迭代对象时从它获取这些索引,请使用enumerate函数
  • 以惯用的方式使用enumerate(以及元组解包)会创建更具可读性和可维护性的代码:

所以这样做:

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

首先,索引将从0到4。编程语言从0开始计数;不要忘记这一点,否则你会遇到索引越界异常。在进行循环中,你只需要一个从0到4计数的变量,如下所示:

for x in range(0, 5):

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

要获取索引的值,请使用

list[index]

您可以使用此代码执行此操作:

ints = [8, 23, 45, 12, 78]index = 0
for value in (ints):index +=1print index, value

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

ints = [8, 23, 45, 12, 78]index = 0
for value in (ints):index +=1print index, valueif index >= len(ints)-1:index = 0

访问索引和方法的性能基准测试

访问python3.7中循环中列表索引的最快方法是使用枚举法来处理小型、中型和大型列表。

请参阅下面的代码示例中的不同的方法,它可用于迭代列表和访问索引值,以及其性能指标(我想这对您很有用):

# Using rangedef range_loop(iterable):for i in range(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 + itemindex += 1

请参阅下面每个方法的性能指标:

from timeit import timeit
def measure(l, number=10000):print("Measure speed for list with %d items" % len(l))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 speed for list with 1000 itemsmeasure(range(1000))# range:  1.161622366# enumerate:  0.5661940879999996# manual_indexing:  0.610455682
# Measure speed for list with 100000 itemsmeasure(range(10000))# range:  11.794482958# enumerate:  6.197628574000001# manual_indexing:  6.935181098000001
# Measure speed for list with 10000000 itemsmeasure(range(10000000), number=100)# range:  121.416859069# enumerate:  62.718909123# manual_indexing:  69.59575057400002

因此,当需要索引时,使用enumerate方法是迭代最快的方法。

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

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

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

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

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

  1. 创建一个变量来保存索引(使用#0

for index in range(len(lst)):   # or xrange# you will have to write extra code to get the element
  1. 创建一个变量来保存索引(使用#0

index = 0while index < len(lst):# You will have to write extra code to get the elementindex += 1  # escape infinite recursion
  1. 总有别的办法的

如前所述,还有其他方法可以做到这一点,这里没有解释,它们甚至可能在其他情况下更适用。例如,使用itertools.chain和for。它比其他示例更好地处理嵌套循环。

你也可以试试这个:

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

这很好地达到了目的:

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

要使用进行循环在列表推导中打印(index, value)的元组:

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

您可以使用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的方法,但使用列表理解,使其以更少的代码更快。

如果我要迭代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])

如果列表中没有重复值:

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

在你的问题中,你写"如何访问循环索引,在这种情况下从1到5?"

但是,列表的索引从零开始运行。因此,我们需要知道您实际上想要的是列表中每个项目的索引和项目,还是您真的想要从1开始的数字。幸运的是,在Python中,很容易做到其中之一或两者兼而有之。

首先,为了澄清,enumerate函数迭代地返回列表中每个项目的索引和对应项。

alist = [1, 2, 3, 4, 5]
for n, a in enumerate(alist):print("%d %d" % (n, a))

上面的输出是,

0 11 22 33 44 5

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

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

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

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

0 21 32 4

这将我们带到enumerate()start=n开关。这只是抵消了索引,您可以等效地简单地在循环内为索引添加一个数字。

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

其输出为

1 12 23 34 45 5

以下是如何使用for-in循环访问索引和数组的元素。

1.使用计数器和+=运算符循环元素。

items = [8, 23, 45, 12, 78]counter = 0
for value in items:print(counter, value)counter += 1

结果:

#    0 8#    1 23#    2 45#    3 12#    4 78

2.使用enumerate()方法循环元素。

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)

3.分别使用indexvalue

items = [8, 23, 45, 12, 78]
for index, value in enumerate(items):print("index", index, "for value", value)

结果:

#    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

4.您可以将index数字更改为任何增量。

items = [8, 23, 45, 12, 78]
for i, value in enumerate(items, start=1000):print(i, value)

结果:

#    1000 8#    1001 23#    1002 45#    1003 12#    1004 78

5.自动计数器递增range(len(...))

items = [8, 23, 45, 12, 78]
for i in range(len(items)):print("Index:", i, "Value:", items[i])

结果:

#    ('Index:', 0, 'Value:', 8)#    ('Index:', 1, 'Value:', 23)#    ('Index:', 2, 'Value:', 45)#    ('Index:', 3, 'Value:', 12)#    ('Index:', 4, 'Value:', 78)

6.使用for-in循环内部函数。

items = [8, 23, 45, 12, 78]
def enum(items, start=0):counter = start
for value in items:print(counter, value)counter += 1    
enum(items)

结果:

#    0 8#    1 23#    2 45#    3 12#    4 78

7.当然,我们不能忘记while循环。

items = [8, 23, 45, 12, 78]counter = 0
while counter < len(items):print(counter, items[counter])counter += 1

结果:

#    0 8#    1 23#    2 45#    3 12#    4 78

8.yield语句返回生成器对象。

def createGenerator():items = [8, 23, 45, 12, 78]
for (j, k) in enumerate(items):yield (j, k)        

generator = createGenerator()
for i in generator:print(i)

结果:

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

9.使用for-in循环和lambda的内联表达式。

items = [8, 23, 45, 12, 78]
xerox = lambda upperBound: [(i, items[i]) for i in range(0, upperBound)]print(xerox(5))

结果:

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

使用循环的简单答案:

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

输出:

Item  1  =  8Item  2  =  23Item  3  =  45Item  4  =  12Item  5  =  78

您可以简单地使用count等变量来计算列表中元素的数量:

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

您可以使用enumerate并在字符串文字中嵌入表达式来获取解决方案。

这是一个简单的方法:

a=[4,5,6,8]for b, val in enumerate(a):print('item #{} = {}'.format(b+1, val))

将“计数器”变量设置为初始化器的循环,该初始化器将在格式化字符串时作为参数,作为项目编号。

进行循环访问作为列表的“listos”变量。当我们通过“i”访问列表时,“i”被格式化为项目价格(或任何它是什么)。

listos = [8, 23, 45, 12, 78]counter = 1for i in listos:print('Item #{} = {}'.format(counter, i))counter += 1

输出:

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

它可以通过以下代码实现:

xs = [8, 23, 45]for x, n in zip(xs, range(1, len(xs)+1)):print("item #{} = {}".format(n, x))

这里,range(1, len(xs)+1);如果您希望输出从1而不是0开始,则需要从1开始范围并将1添加到估计的总长度,因为python默认从0开始索引数字。

Final Output:item #1 = 8item #2 = 23item #3 = 45

您可以使用range(len(some_list)),然后像这样查找索引

xs = [8, 23, 45]for i in range(len(xs)):print("item #{} = {}".format(i + 1, xs[i]))

或者使用Python的内置enumerate函数,它允许您循环遍历列表并检索列表中每个项目的索引和值

xs = [8, 23, 45]for idx, val in enumerate(xs, start=1):print("item #{} = {}".format(idx, val))

除了上面所有优秀的答案之外,这里还有一个在使用熊猫系列对象时解决此问题的方法。在许多情况下,熊猫系列具有无法使用enumerate()函数访问的自定义/唯一索引(例如,唯一标识符字符串)。

xs = pd.Series([8, 23, 45])
xs.index = ['G923002', 'G923004', 'G923005']
print(xs)

输出:

#    G923002     8#    G923004    23#    G923005    45#    dtype: int64

我们可以在下面看到enumerate()没有给我们想要的结果:

for id, x in enumerate(xs):print("id #{} = {}".format(id, x))

输出:

#    id #0 = 8#    id #1 = 23#    id #2 = 45

我们可以使用.items()在for循环中访问熊猫系列的索引:

for id, x in xs.items():print("id #{} = {}".format(id, x))

输出:

#    id #G923002 = 8#    id #G923004 = 23#    id #G923005 = 45

单线爱好者:

[index for index, datum in enumerate(data) if 'a' in datum]

解释:

>>> data = ['a','ab','bb','ba','alskdhkjl','hkjferht','lal']>>> data['a', 'ab', 'bb', 'ba', 'alskdhkjl', 'hkjferht', 'lal']>>> [index for index, datum in enumerate(data) if 'a' in datum][0, 1, 3, 4, 6]>>> [index for index, datum in enumerate(data) if 'b' in datum][1, 2, 3]>>>

采取的措施:

  • Pythonlist不提供索引;如果您使用for
  • 如果你enumerate一个list,它会返回你另一个list
    • 但是这个列表会有不同的类型
    • 它将用索引tuple包装每个元素
    • 我们可以将元组作为变量访问,用逗号分隔(,

谢谢。让我在你的祈祷。