用下面的例子列表:L = ['a','b','c','d']
如何在循环列表中循环,同时在当前元素前面和后面查看?
我想达到以下的输出:
>>> a d b
>>> b a c
>>> c b d
>>> d c a
伪代码将是:
for e in L:
print(e, letter_before_e, letter_after_e
用下面的例子列表:L = ['a','b','c','d']
如何在循环列表中循环,同时在当前元素前面和后面查看?
我想达到以下的输出:
>>> a d b
>>> b a c
>>> c b d
>>> d c a
伪代码将是:
for e in L:
print(e, letter_before_e, letter_after_e
你几乎有
for i, e in enumerate(L):
print(e, L[i-1], L[(i+1) % len(L)])
编辑追加MOD
你可以只在L
循环,采用i
减号加上1模得到上一个和下一个元素。
,很可能会矫枉过正,在这种情况下,但这是一般使用情况的循环双向链表http://ada.rg16.asn-wien.ac.at/~python/how2think/english/chap17.htm
在我的代码,我会用3 moving window一个元件在通过最后一个元素前置和附加的第一元素列表:
from itertools import tee, izip, chain
def window(iterable,n):
'''Moving window
window([1,2,3,4,5],3) -> (1,2,3), (2,3,4), (3,4,5)
'''
els = tee(iterable,n)
for i,el in enumerate(els):
for _ in range(i):
next(el, None)
return izip(*els)
def chunked(L):
it = chain(L[-1:], L, L[:1]) # (1,2,3,4,5) -> (5,1,2,3,4,5,1)
for a1,a2,a3 in window(it,3): # (3,1,2,3,1) -> (3,1,2), (1,2,3), (2,3,1)
yield (a2,a1,a3)
## Usage example ##
L = ['a','b','c','d']
for t in chunked(L):
print(' '.join(t))
从概念上来说,保持跟踪项目往往比较简单,而不是展望未来。 deque
班是理想的跟踪n
以前的项目,因为它可以让你设置一个最大长度;追加新项目会自动推送旧项目。
from collections import deque
l = ['a','b','c','d']
d = deque(l[-2:], maxlen=3)
for e in l:
d.append(e)
print d[1], d[0], d[2]
在这种解决方案的唯一区别是,d c a
会第一,而不是最后一次。如果这很重要,你可以开始,就像你已经看到一个迭代:
from collections import deque
l = ['a','b','c','d']
d = deque(l[-1:] + l[:1], maxlen=3)
for e in l[1:] + l[:1]:
d.append(e)
print d[1], d[0], d[2]
你将有超出范围的问题。因为[3 + 1]超出范围。 – User007 2012-08-17 18:04:55
谢谢,现在修复。 – Phil 2012-08-17 18:06:07