Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python standard library function for rearranging a list

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,

like image 882
alwbtc Avatar asked Aug 21 '11 22:08

alwbtc


2 Answers

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)
like image 161
zeekay Avatar answered Nov 09 '22 22:11

zeekay


>>> ((a+a[:0:-1])*len(a))[::len(a)][:len(a)]
[1, 7, 2, 6, 3, 5, 4]
like image 22
John La Rooy Avatar answered Nov 09 '22 20:11

John La Rooy