Python 使用列表元素的索引进行列表迭代

Python 使用列表元素的索引进行列表迭代,python,Python,我想以特定的方式访问列表项。例如 l1 =[1,2,3,4,5] 现在我想访问列表中的第三个元素,即4,但我想以特定的方式获得结果 我想让程序得到第二个元素,即3,并使用它的索引,我想找到第三个元素 总之 print l1[index] index2 = index+1 print l1[index2] 我怎样才能完成这项任务?有没有其他有效的方法来完成这项任务 谢谢以下是一种使用以下方法的方法: 这个输出 Current 1 Next 2 Current 2 Next 3 Curren

我想以特定的方式访问列表项。例如

l1 =[1,2,3,4,5]
现在我想访问列表中的第三个元素,即4,但我想以特定的方式获得结果

我想让程序得到第二个元素,即3,并使用它的索引,我想找到第三个元素

总之

print l1[index]

index2 = index+1

print l1[index2]
我怎样才能完成这项任务?有没有其他有效的方法来完成这项任务

谢谢

以下是一种使用以下方法的方法:

这个输出

Current 1
Next 2
Current 2
Next 3
Current 3
Next 4
Current 4
Next 5
Current 5
Next 5 is the last item in the list
>>> 
也可以从索引1开始枚举,在查找下一项时不添加到索引:

>>> for i, elem in enumerate(l1, start=1):
...     print 'Current', elem
...     try:
...         print 'Next', l1[i]
...     except IndexError:
...         print '%d is the last item in the list' % elem
...         
Current 1
Next 2
Current 2
Next 3
Current 3
Next 4
Current 4
Next 5
Current 5
Next 5 is the last item in the list
>>> 
我想让程序得到第二个元素,即3,并使用它的索引,我想找到第三个元素


最终目标是什么?您可以执行
i=l1。索引(4)
然后执行
l1[i+1]
,但这只会返回第一个匹配的索引(
['a','b','a'])。索引('a')
0
)。你想做什么?我想打印第I个元素并使用它的索引我想打印第I+1个元素如果
I
th元素是最后一个呢?这个问题让我很困惑。我想你会想要
打印l1[l1[索引]]
,但我不认为这是你想要的?这是另一件事,但我问这个问题是为了执行一些其他任务,我不必担心这个条件。好吧,让我试试这个,也许OP会在解释为什么这是错误的时候,更多地阐明他的要求。
>>> for i, elem in enumerate(l1, start=1):
...     print 'Current', elem
...     try:
...         print 'Next', l1[i]
...     except IndexError:
...         print '%d is the last item in the list' % elem
...         
Current 1
Next 2
Current 2
Next 3
Current 3
Next 4
Current 4
Next 5
Current 5
Next 5 is the last item in the list
>>> 
i = 1         # Get the 2nd element
print l1[i+1] # Using its index find the 3rd element.