I have a list:

[a, b, c, d, e, f, g, h, i, j, k, l, m,  n, o, p]

I would like 4 lists:

[a, e, i, m]
[b, f, j, n]
[c, g, k, o]
[d, h, l, p]

How would I go about this?
Thanks.

Edited 4 Years Ago by floatingshed: n/a

Sorry, mislead you by over simplifying the question...
The main list will have full paths to files in it, not simple one-character elements. They will vary in length significantly.

Sorry, mislead you by over simplifying the question...
The main list will have full paths to files in it, not simple one-character elements. They will vary in length significantly.

It works nonetheless. Try to call splitIt(4, yourlist).

Are we at crossed purposes here? I don't want my list in equal pieces. I want elements 0,4,8,12 in one new list, elements 1,5,9,13 in another new list etc Or even simpler elements 0,1,2,3 elements 4,5,6,7 elements 8,9,10,11 in new lists (workable but not as elegant for me).

Are we at crossed purposes here? I don't want my list in equal pieces. I want elements 0,4,8,12 in one new list, elements 1,5,9,13 in another new list etc Or even simpler elements 0,1,2,3 elements 4,5,6,7 elements 8,9,10,11 in new lists (workable but not as elegant for me).

Oh, then try

[list(x) for x in zip(*splitIt(4, yourlist))]

Edited 4 Years Ago by Gribouillis: n/a

It is Python idiom for transposing values (assuming that count of elements is divisible by the row length)

>>> v = "abcdefghijklmnop"
>>> m = [a+b+c+d for a,b,c,d in zip(v[::4], v[1::4], v[2::4], v[3::4])]
>>> m
['abcd', 'efgh', 'ijkl', 'mnop']
>>> m = [a+b+c+d for a,b,c,d in zip(*zip(v[::4], v[1::4], v[2::4], v[3::4]))]
>>> m
['aeim', 'bfjn', 'cgko', 'dhlp']
>>>

One simple way to sample a list while skipping elements with with the following syntax.

a=[1,2,3,4,5]
b=a[::2]  #means sample all elements with spacing = 2
print b
>>>[1,3,5]

c=a[2::2]  #means sample all elements with spacing =2 starting from the 3rd element
This article has been dead for over six months. Start a new discussion instead.