2012-06-30 24 views
1
my_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 

使用Python一个“矩阵”式的格式,我需要显示为列表:1.4.3列表Python中

one, two, three 
four, five, six 
seven 

我需要的是灵活,因为该列表会经常改变。

回答

7

您可以从itertools使用石斑鱼recipe

def grouper(n, iterable, fillvalue=None): 
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return izip_longest(fillvalue=fillvalue, *args) 

使用这样的:

for line in grouper(3, my_list): 
    print ', '.join(filter(None, line)) 

看到它联机工作:ideone

0
def matprint(L, numcols): 
    for i,item in enumerate(L): 
     print item, 
     if i and not (i+1)%numcols: 
      print '\n', 

>>> my_list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 
>>> matprint(my_list, 3) 
one two three 
four five six 
seven