Python 如何循环浏览循环列表,同时查看当前元素的前后?
使用以下示例列表:Python 如何循环浏览循环列表,同时查看当前元素的前后?,python,Python,使用以下示例列表: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,然后取索引i减去和加1模len(L),得到上一个和下一个元素。在这种情况下可能会有点过分,但这是循环双链接列表的一般使用
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
,然后取索引i
减去和加1模len(L)
,得到上一个和下一个元素。在这种情况下可能会有点过分,但这是循环双链接列表的一般使用情况
for i, e in enumerate(L):
print(e, L[i-1], L[(i+1) % len(L)])
编辑以在我的代码中添加mod,我将在最后一个元素前面和第一个元素后面的列表中使用3个元素:
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]超出范围。