Reputation: 181
How to traverse a list until it reaches the last element, then traverse it backwards until it reaches the 1st element, then repeat?
In other wards, how can iterate through a list specifically in a pattern that bounces off the 1st and last element?
e.g For a list of length=3
time=1, index=0
time=2, index=1
time=3, index=2
time=4, index=1
time=5, index=0
time=6, index=1
time=7, index=2
Upvotes: 0
Views: 136
Reputation: 181
I also found that the index can also be calculated using
index = (time-1)%(2*length-2)
Upvotes: 0
Reputation: 11602
One way using itertools.cycle
:
from itertools import cycle
lst = [0, 1, 2]
res1 = cycle(lst + lst[-2:0:-1])
In [143]: [next(q.res1) for _ in range(10)]
Out[143]: [0, 1, 2, 1, 0, 1, 2, 1, 0, 1]
Thanks to @Chris_Rands for pointing out that the list comprehension can be replaced nicely with list(itertools.islice(res1, 10))
.
Upvotes: 2
Reputation: 5503
If you actually start with a list you can use slice and reversed to bounce it once like this:
def bounce(a_list):
yield from a_list
yield from reversed(a_list[1:-1])
for x in bounce([1, 2, 3, 4]):
print(x)
Repeat the bouncyness for added fun.
for x in itertools.cycle(bounce([0, 1, 2])):
print(x)
Upvotes: 3