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

에서 "매트릭스"타입 형식 목록을 출력하는 I는 다음과 같이 표시 할 목록을 필요로한다.파이썬 파이썬 사용

답변

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