'Rearrange a python list into n lists, by column

I want to rearrange a list l into a list of n lists, where n is the number of columns.

e.g.,

l = [1,2,3,4,5,6,7,8,9,10]
n = 4
==> [[1,5,9],[2,6,10],[3,7][4,8]]

Can someone please help me out with an algorithm? Feel free to use any python awesomeness that's available; I'm sure theres some cool mechanism that's a good fit for this, i just can't think of it.

PS The example list just happened to be ordered numbers starting at 1. That's not my actual scenario.



Solution 1:[1]

l = [1,2,3,4,5,6,7,8,9,10]
n = 4

def f(l,n):
    A = []
    [A.append([]) for i in xrange(n)] 
    [ A [(i - 1) % n].append(i) for i in l]
    return A

print f(l,n)

[[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]

Solution 2:[2]

The following function does what you want to achieve:

def rearrange(seq,n):
    return [[v for i,v in enumerate(seq[x:]) if i%n==0] for x in xrange(len(seq))][:n]

Solution 3:[3]

Writing Python isn't a game of code golf, don't be afraid to use more than one line for the sake of readability.

l = [1,2,3,4,5,6,7,8]

def split_into_columns(input_list, num_of_cols=3):
    retval = [ [] for _ in xrange(num_of_cols)]      # build 3 columns
    for i in xrange(len(input_list)):                # iterate through original list
        retval[i%num_of_cols].append(input_list[i])  # place in the "modulo 3" column
    return retval

    # here's a compressed, less readable version of that for-loop
    #[retval[i%3].append(input_list[i]) for i in xrange(len(input_list))]
    #return retval

print split_into_columns(l, 3)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jimifiki
Solution 2
Solution 3