The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).
I've thought about two unpythonic ways of doing it:
def pairs(lst):
n = len(lst)
for i in range(n):
yield lst[i],lst[(i+1)%n]
and:
def pairs(lst):
return zip(lst,lst[1:]+[lst[:1]])
expected output:
>>> for i in pairs(range(10)):
print i
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
(7, 8)
(8, 9)
(9, 0)
>>>
any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?
also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…