2010-03-22 79 views
4

我有一个项目的名单按字母顺序排序:显示的项目列表中垂直表,而不是horizo​​nally

mylist = [a,b,c,d,e,f,g,h,i,j] 

我能够输出列表在HTML表格horizo​​nally像这样:

| a , b , c , d | 
| e , f , g , h | 
| i , j , , | 

什么是算法来垂直创建表是这样的:

| a , d , g , j | 
| b , e , h , | 
| c , f , i , | 

我使用Python,但你答案可以是任何语言,甚至是伪代码。

+2

这是一个好主意,不使用'list'作为变量名。它影响内置 – 2010-03-22 21:30:01

回答

9
>>> 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]] 

由你想要的结果的行数替换3

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

非常优雅的解决方案! – mojbro 2010-03-22 19:40:27

+0

@vishvananda:不,这两个数字都是生成的行数。我已经添加了另一个例子。 – balpha 2010-03-22 20:21:34

+0

你当然是正确的。我的大脑未能正确解析数组切片:)。这就是我没有检查出壳 – vishvananda 2010-03-22 20:29:06

0

这里是一个可行的粗溶液(打印数从0到N-1含):

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 '' 

这只是打印数字,例如与NROWS = 3N = 22

0 3 6 9 12 15 18 21 
1 4 7 10 13 16 19 
2 5 8 11 14 17 20 

可以轻松适应打印任何你想要的东西,并添加所需的格式。

0
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"); 
} 
0

这是我想做到这一点。给定l(整数,在这个例子中)的列表。

  • 决定列(或行)的数目和,
  • 计算所需的行(或列)的数目。
  • 然后循环遍历它们,逐行打印相应的值。

见下面的代码:

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 

最佳,

菲利普

1
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, | 
+0

我喜欢这个,+1 – 2010-03-22 20:34:26

0
>>> 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')