2012-06-30 25 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