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

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

如何访问如下列表的索引本身?

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

当我使用for循环,在本例中,如何访问循环索引(从1到5)?


慕田峪7331174
浏览 736回答 3
3回答

宝慕林4294392

使用for循环,在本例中如何访问循环索引(从1到5)?使用enumerate若要在迭代时使用元素获取索引,请执行以下操作:for&nbsp;index,&nbsp;item&nbsp;in&nbsp;enumerate(items): &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;item)请注意,Python的索引从零开始,所以上面的内容可以得到0到4。如果要计数1到5,请执行以下操作:for&nbsp;count,&nbsp;item&nbsp;in&nbsp;enumerate(items,&nbsp;start=1): &nbsp;&nbsp;&nbsp;&nbsp;print(count,&nbsp;item)统一控制流您所要求的是下面的Pythonic等价物,这是大多数低级语言程序员都会使用的算法:index&nbsp;=&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Python's&nbsp;indexing&nbsp;starts&nbsp;at&nbsp;zerofor&nbsp;item&nbsp;in&nbsp;items:&nbsp;&nbsp;&nbsp;#&nbsp;Python's&nbsp;for&nbsp;loops&nbsp;are&nbsp;a&nbsp;"for&nbsp;each"&nbsp;loop&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;item) &nbsp;&nbsp;&nbsp;&nbsp;index&nbsp;+=&nbsp;1或者使用没有for-each循环的语言:index&nbsp;=&nbsp;0while&nbsp;index&nbsp;<&nbsp;len(items): &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;items[index]) &nbsp;&nbsp;&nbsp;&nbsp;index&nbsp;+=&nbsp;1或者有时更常见(但在Python中是统一的):for&nbsp;index&nbsp;in&nbsp;range(len(items)): &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;items[index])使用枚举函数Python的enumerate功能通过隐藏索引的计算,并将可迭代封装到另一个可迭代(enumerate对象),它生成索引的两个项元组和原始可迭代提供的项。看起来是这样的:for&nbsp;index,&nbsp;item&nbsp;in&nbsp;enumerate(items,&nbsp;start=0):&nbsp;&nbsp;&nbsp;#&nbsp;default&nbsp;is&nbsp;zero &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;item)此代码示例非常好典范Python惯用代码与非Python代码之间区别的例子。惯用代码是复杂的(但并不复杂)Python,其编写方式与预期的使用方式相同。该语言的设计者期望使用惯用的代码,这意味着通常这些代码不仅具有更高的可读性,而且更有效率。数一数即使你不需要索引,但你需要一个迭代计数(有时是可取的),你可以从1最后一个数字就是你的数字。for&nbsp;count,&nbsp;item&nbsp;in&nbsp;enumerate(items,&nbsp;start=1):&nbsp;&nbsp;&nbsp;#&nbsp;default&nbsp;is&nbsp;zero &nbsp;&nbsp;&nbsp;&nbsp;print(item)print('there&nbsp;were&nbsp;{0}&nbsp;items&nbsp;printed'.format(count))当您说您希望从1到5之间时,计数似乎更符合您的要求(而不是索引)。一步的解释要细分这些示例,假设我们有一个要用索引迭代的项列表:items&nbsp;=&nbsp;['a',&nbsp;'b',&nbsp;'c',&nbsp;'d',&nbsp;'e']现在,我们将这个迭代传递给枚举,创建一个枚举对象:enumerate_object&nbsp;=&nbsp;enumerate(items)&nbsp;#&nbsp;the&nbsp;enumerate&nbsp;object我们可以从这个可迭代的项目中提取第一个项目,这样我们就可以在循环中使用next职能:iteration&nbsp;=&nbsp;next(enumerate_object)&nbsp;#&nbsp;first&nbsp;iteration&nbsp;from&nbsp;enumerateprint(iteration)我们看到我们得到了一个元组0,第一个索引,以及'a',第一项:(0,&nbsp;'a')我们可以使用所谓的“序列解列“从这两个元组中提取元素:index,&nbsp;item&nbsp;=&nbsp;iteration#&nbsp;&nbsp;&nbsp;0,&nbsp;&nbsp;'a'&nbsp;=&nbsp;(0,&nbsp;'a')&nbsp;#&nbsp;essentially&nbsp;this.当我们检查index,我们发现它引用了第一个索引,0,和item指的是第一项,'a'.>>>&nbsp;print(index)0>>>&nbsp;print(item)a结语Python索引从零开始若要在迭代过程中从可迭代的对象中获取这些索引,请使用枚举函数。以惯用的方式使用枚举(连同元组解压缩)创建的代码更具可读性和可维护性:所以这样做:for&nbsp;index,&nbsp;item&nbsp;in&nbsp;enumerate(items,&nbsp;start=0):&nbsp;&nbsp;&nbsp;#&nbsp;Python&nbsp;indexes&nbsp;start&nbsp;at&nbsp;zero &nbsp;&nbsp;&nbsp;&nbsp;print(index,&nbsp;item)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python