I am wondering if there is a standard library function in Python which will rearrange the elements of a list like below:
a = [1,2,3,4,5,6,7]
function(a)
print a
a = [1,7,2,6,3,5,4]
It should get one element from beginning of original list, then one from end, then second from beginning and so on. Then rearrange the list.
Regards,
You could build a fast, memory efficient generator using itertools
which does what you want:
from itertools import chain, izip
def reorder(a):
gen = chain.from_iterable(izip(a, reversed(a)))
for _ in a:
yield next(gen)
>>> list(reorder(a))
<<< [1, 7, 2, 6, 3, 5, 4]
You'll find that itertools
has a great collection of building blocks for creating your own efficient iterators. A slightly more succinct solution:
>>> list(chain.from_iterable(izip(a, reversed(a))))[:len(a)]
<<< [1, 7, 2, 6, 3, 5, 4]
List comprehensions are another really concise way to build lists:
>>> [x for t in zip(a, reversed(a)) for x in t][:len(a)]
<<< [1, 7, 2, 6, 3, 5, 4]
Finally here's a short one-liner just for fun:
>>> sum(zip(a, a[::-1]), ())[:len(a)]
<<< (1, 7, 2, 6, 3, 5, 4)
>>> ((a+a[:0:-1])*len(a))[::len(a)][:len(a)]
[1, 7, 2, 6, 3, 5, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With