I want to loop a list over a cycle. ex: I have three elements in the array L = [1,2,3] I want to get the output as
L[0],L[1]
L[1],L[2]
L[2],L[0]
Is there a easy way get the slightly different output
L[0],L[1]
L[1],L[2]
L[0],L[2]
There is a recipe in the itertools
documentation that you can use:
import itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
Call this with itertools.cycle(L)
and you're good to go:
L = [1, 2, 3]
for pair in pairwise(itertools.cycle(L)):
print pair
# (1, 2)
# (2, 3)
# (3, 1)
# (1, 2)
# ...
Did you mean combinations? http://en.wikipedia.org/wiki/Combination
from itertools import combinations
comb = []
for c in combinations([1, 2, 3], 2):
print comb.append(c)
For sorting you can use then
sorted(comb, key=lambda x: x[1])
Output:
[(1, 2), (1, 3), (2, 3)]
Using modulus operator
Using
itertools.cycle
As for your output, you could just do this.