-3

I am looking to divide a list into 3 parts in python. If the list doesn't divide by 3, I would like it to 'fill' the first column then the second, then the third.

e.g:

1|2|3

1|3|
2|


1|3|
2|4|

1|3|5
2|4|

1|3|5
2|4|6

And so on.

I am currently doing something like this, which doesn't give the desired results. Have also played around with using % to no avail

l = [1,2,3,4,5]
a = [:l/3]
b = [l/3:(l/3)*2 ]
c = [(l/3)*2 :]

All help appreciated, thanks

Note The answer to Splitting a list of into N parts of approximately equal length gives the opposite result, so please don't mark this question as already answered

Community
  • 1
  • 1
holmeswatson
  • 969
  • 3
  • 14
  • 39
  • 6
    I didn't get you. Say the list is `[1,2,3,4,5]`. What o/p do you want? – nitish712 Feb 03 '14 at 13:12
  • What does "fill" mean? What does "doesn't give the desired results" mean? What does `1|2|3` mean? Is that a list? Does it relate with `[1,2,3,4,5]` of the second example in anyway? – Bakuriu Feb 03 '14 at 13:22

3 Answers3

2

There is a recipe in itertools that will do this:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You could use this as-is or modify for your needs.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

Here is some code I just drew up.

import math
startArray = [1,2,3,4,5,6,7,8,9]
secLength = math.ceil(len(startArray) / 3)
newArray = []
newArray.append(startArray[:secLength])
newArray.append(startArray[secLength : 2*secLength])
newArray.append(startArray[2*secLength:]);
print(newArray)

For this example, the return is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

If your array is [1,2,3,4,5,6,7], it returns [[1, 2, 3], [4, 5, 6], [7]]

erdekhayser
  • 6,537
  • 2
  • 37
  • 69
0

Continued to try work this out, got this:

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

col = 3
height = int(math.ceil(len(l)/col))

print height
a = l[:height+1]
b = l[height+1:(height+1)*2]
c = l[(height+1)*2:]

print l
print a
print b
print c
holmeswatson
  • 969
  • 3
  • 14
  • 39