Reputation: 43
I have a list of items sorted alphabetically:
mylist = [a,b,c,d,e,f,g,h,i,j]
I'm able to output the list in an html table horizonally like so:
| a , b , c , d |
| e , f , g , h |
| i , j , , |
What's the algorithm to create the table vertically like this:
| a , d , g , j |
| b , e , h , |
| c , f , i , |
I'm using python, but your answer can be in any language or even pseudo-code.
Upvotes: 4
Views: 6675
Reputation: 304255
>>> import numpy as np
>>> L=['a','b','c','d','e','f','g','h','i','j']
>>> width=4
>>> height = (len(L)-1)/width+1
>>> L=L+[' ']*(width*height-len(L)) #Pad to be even multiple of width
>>> A = np.array([L])
>>> A.shape=(width,height)
>>> A.transpose()
array([['a', 'd', 'g', 'j'],
['b', 'e', 'h', ' '],
['c', 'f', 'i', ' ']],
dtype='|S1')
Upvotes: 0
Reputation: 50918
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> [l[i::3] for i in xrange(3)]
[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
Replace 3
by the number of lines you want as a result:
>>> [l[i::5] for i in xrange(5)]
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
Upvotes: 9
Reputation: 879869
import itertools
def grouper(n, iterable, fillvalue=None):
# Source: http://docs.python.org/library/itertools.html#recipes
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)
def format_table(L):
result=[]
for row in L:
result.append('| '+', '.join(row)+' |')
return '\n'.join(result)
L = ['a','b','c','d','e','f','g','h','i','j']
L_in_rows=list(grouper(3,L,fillvalue=' '))
L_in_columns=zip(*L_in_rows)
print(format_table(L_in_columns))
# | a, d, g, j |
# | b, e, h, |
# | c, f, i, |
Upvotes: 1
Reputation: 1529
This is how I'd do it. Given the list of l
(of integers, in the example).
See code below:
import math
l = [0,1,2,3,4,5,6,7,8,9]
num_cols=4
num_rows=int(math.ceil(1.0*len(l)/num_cols))
for r in range(num_rows):
for c in range(num_cols):
i = num_rows*c + r
if i<len(l):
print '%3d ' % l[i],
else:
print ' - ', # no value
print # linebreak
Best,
Philip
Upvotes: 0
Reputation: 735
int array_size = 26;
int col_size = 4;
for (int i = 0; i <= array_size/col_size; ++i) {
for (int j = i; j < array_size; j += col_size-1) {
print (a[j]);
}
print("\n");
}
Upvotes: -1
Reputation: 273546
Here's a rough solution that works (prints numbers from 0 to N-1 inclusive):
import math
NROWS = 3
N = 22
for nr in xrange(NROWS):
for nc in xrange(int(math.ceil(1.0 * N/NROWS))):
num = nc * NROWS + nr
if num < N:
print num,
print ''
This just print numbers, for example with NROWS = 3
and N = 22
:
0 3 6 9 12 15 18 21
1 4 7 10 13 16 19
2 5 8 11 14 17 20
You can easily adapt it to print anything you want of course and add the required formatting.
Upvotes: 0