可能在没有索引的for循环中引用列表条目?

use*_*860 5 python indexing loops

关于python for循环特别感兴趣的问题.工程程序通常需要先前或未来索引的值,例如:

for i in range(0,n):
    value = 0.3*list[i-1] + 0.5*list[i] + 0.2*list[i+1]
Run Code Online (Sandbox Code Playgroud)

等等...

但是我更喜欢漂亮干净的python语法:

for item in list:
    #Do stuff with item in list
Run Code Online (Sandbox Code Playgroud)

或者对于2d点数据的列表:

for [x,y] in list:
    #Process x, y data
Run Code Online (Sandbox Code Playgroud)

我喜欢循环遍历列表而不明确使用索引来引用列表中的项目的概念.我想知道是否有一个干净的方法来抓住上一个或下一个项目而不循环索引(或没有独立跟踪索引)?

编辑:

感谢Andrew Jaffe(以及代理Mark Byers)和gnibbler的简单,可扩展的示例.到目前为止,我还没有意识到itertools或nwise模块.John Machin - 感谢非常复杂的例子.你在这个例子中付出了很多努力,显然我提出的一些递归算法不能生成与输入列表具有相同元素数量的列表,如果不使用显式索引则会出现问题.像这样的算法通常会出现在信号处理中.

And*_*ffe 4

这是一个基于itertools成对代码的配方,它执行一般的 n 向分组:

import itertools

def nwise(iterable, n=2):
    "s->(s_0,s_1, ..., s_n), (s_1,s_2,..., s_n+1), ... "
    ntup = itertools.tee(iterable, n)
    for i, item in enumerate(ntup):
        for ii in range(i):
            next(item, None)
    return itertools.izip(*ntup)
Run Code Online (Sandbox Code Playgroud)

可以这样使用:

>>> import nwise
>>> ll = range(10)
>>> for tup in nwise.nwise(ll,3): print tup
... 
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
(6, 7, 8)
(7, 8, 9)
Run Code Online (Sandbox Code Playgroud)

[感谢马克·拜尔斯对这个想法的回答]