Construct A Circular Loop In Python
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 slight
Solution 1:
Using modulus operator
>>> a = [1,2,3]
>>> for x inrange(10):
print a[x % len(a)]
Using itertools.cycle
>>> iterator = cycle(a)
>>> for _ inrange(10):
printnext(iterator)
As for your output, you could just do this.
>>> for x inrange(10):
print'{0}, {1}'.format(a[x % len(a)], a[(x+1) % len(a)])
>>> 1, 2>>> 2, 3>>> 3, 1... etc etc
Solution 2:
You can just use increasing index, and use modulo (remainder of division)
myList = [1,2,3]
for i in xrange(len(myList)):
myTuple = (myList[i],myList[(i+1)%len(myList)])
print myTuple
will produce:
(1,2)
(2,3)
(3,1)
Solution 3:
You could try something like
L = [1,2,3]
length = len(L)
for i in xrange(length):
print L[i % length], L[(i+1) % length]
Output
1 2
2 3
3 1
This way, you can do something like xrange(10)
and still have it cycle:
1 2
2 3
3 1
1 2
2 3
3 1
1 2
2 3
3 1
1 2
Solution 4:
l = [0,1,2,3]
for i in xrange(0, len(l)):
print l[i], l[(i+1) % len(l)]
01122330
Solution 5:
There is a recipe in the itertools
documentation that you can use:
import itertools
defpairwise(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)# ...
Post a Comment for "Construct A Circular Loop In Python"