Skip to content Skip to sidebar Skip to footer

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 pl

Solution 1:

There is indeed a cool mechanism for this in Python: the three-argument form of slicing, where the last argument is step size.

>>>l = [1,2,3,4,5,6,7,8,9,10]>>>n = 4>>>[l[i::n] for i in xrange(n)]
[[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]

Solution 2:

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 3:

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] forx in xrange(len(seq))][:n]

Solution 4:

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]

defsplit_into_columns(input_list, num_of_cols=3):
    retval = [ [] for _ in xrange(num_of_cols)]      # build 3 columnsfor i in xrange(len(input_list)):                # iterate through original list
        retval[i%num_of_cols].append(input_list[i])  # place in the "modulo 3" columnreturn 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 retvalprint split_into_columns(l, 3)

Post a Comment for "Rearrange A Python List Into N Lists, By Column"