Given a list
a = [0,1,2,3,4,5,6,7,8,9]
how can I get
b = [0,9,1,8,2,7,3,6,4,5]
That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
Given a list
a = [0,1,2,3,4,5,6,7,8,9]
how can I get
b = [0,9,1,8,2,7,3,6,4,5]
That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?
You can partition the list into two parts about the middle, reverse the second half and zip the two partitions, like so:
Output:
Not at all elegant, but it is a clumsy one-liner:
Note that it assumes you are doing this for a list of even length. If that breaks, then this breaks (it drops the middle term). Note that I got some of the idea from here.
Note:
Use the right toolz.
First, I tried something similar to Raymond Hettinger's solution with itertools (Python 3).
cycle
between getting items from the forwarditer
and thereversed
one. Just make sure you stop atlen(a)
withislice
.This can easily be put into a single line but then it becomes much more difficult to read:
Putting it in one line would also prevent you from using the other half of the iterators if you wanted to:
Not sure, whether this can be written more compactly, but it is efficient as it only uses iterators / generators