2

我有一个包含 107 个名称的列表,我想以 3 个左右为一组打印出来,每个名称用制表符分隔,每行后有一个换行符,直到最后。我怎样才能做到这一点?

当然,for item in list print item我每行只有 1 个名字,我想这很好,但我想一次在控制台中容纳更多,所以当我浏览列表时,我想在每行打印 3 个左右的名字,所以而不是:

name1
name2
name3
name4
name5
name6

我会得到:

name1     name2     name3
name4     name5     name6

寻找这个问题的答案有点困难,我无法想出我需要或我能理解的东西,我发现的大多数事情都只是处理len()range()让我感到困惑。有一些简单的方法可以做到这一点吗?谢谢!

[编辑:更新] 使用@inspectorG4dget 的示例:

for i in range(0, len(listnames), 5):
    print '\t\t'.join(listnames[i:i+5])

我得到以下信息: http: //www.pasteall.org/pic/show.php?id=41159

我怎样才能清理干净,以便每列中的所有内容都很好地对齐?我想要的可以轻松做到吗?

4

4 回答 4

5

1)

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'ii','uuuuuuuuuuuuuuuuuuu','aaa',
      'round','flat','sharp',
      'blueberry','banana','apple',
      'red','purple','white',
      'hen','tiger']

a,b = divmod(len(li),3)
itn = iter(li).next
print ''.join('%s\t%s\t%s\n' % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%s\t%s\t\n' % (itn(),itn()) if b==2
         else '%s\t\n' % itn() if b==1
         else '')

结果

sea mountain    desert
Emma    Cathy   Kate
ii  uuuuuuuuuuuuuuuuuuu aaa
round   flat    sharp
blueberry   banana  apple
red purple  white
hen tiger   

.

2)

并在宽度取决于列表中最长元素的列中对齐:

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'blueberry','banana','apple',
      'red','purple','white',
      'hen','tiger']

maxel = max(len(el) for el in li)
a,b = divmod(len(li),3)
itn = iter(li).next
form = '%%-%ds\t%%-%ds\t%%-%ds\n' % (maxel,maxel,maxel)
print ''.join(form % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%%-%ds\t%%-%ds\t\n' %(maxel,maxel) % (itn(),itn()) if b==2
         else '%%-%ds\t\n' % ma% itn() if b==1
         else '')

结果

sea         mountain    desert   
Emma        Cathy       Kate     
HH          VVVVVVV     AAA      
round       flat        sharp    
blueberry   banana      apple    
red         purple      white    
hen         tiger       

.

3)

要在列中对齐,每列的宽度取决于其中最长的元素:

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'red','purple','white',
      'hen','tiger']

maxel0 = max(len(li[i]) for i in xrange(0,len(li),3)) 
maxel1 = max(len(li[i]) for i in xrange(1,len(li),3))
maxel2 = max(len(li[i]) for i in xrange(2,len(li),3))
a,b = divmod(len(li),3)
itn = iter(li).next
form = '%%-%ds\t%%-%ds\t%%-%ds\n' % (maxel0,maxel1,maxel2)
print ''.join(form % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%%-%ds\t%%-%ds\t\n' %(maxel0,maxel1) % (itn(),itn()) if b==2
         else '%%-%ds\t\n' % maxel0 % itn() if b==1
         else '')

结果

sea     mountain    desert
Emma    Cathy       Kate  
HH      VVVVVVV     AAA   
round   flat        sharp 
nut     banana      apple 
red     purple      white 
hen     tiger       

4)

我已经修改了算法,以便推广到想要的任意数量的列。
所需的列数必须作为参数传递给 parameter nc

from itertools import imap,islice

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'heeeeeeeeeeen','tiger','snake'
      'red','purple','white',
      'atlantic','pacific','antarctic',
      'Bellini']

print 'len of li == %d\n' % len(li)

def cols_print(li,nc):
    maxel = tuple(max(imap(len,islice(li,st,None,nc)))
                  for st in xrange(nc))

    nblines,tail = divmod(len(li),nc)
    stakes = (nc-1)*['%%-%ds\t'] + ['%%-%ds']
    form = ''.join(stakes) % maxel

    itn = iter(li).next

    print '\n'.join(form % tuple(itn() for g in xrange(nc))
                  for i in xrange(nblines)) 
    if tail:
        print ''.join(stakes[nc-tail:]) % maxel[0:tail] % tuple(li[-tail:]) + '\n'
    else:
        print


for nc in xrange(3,8):
    cols_print(li,nc)
    print '-----------------------------------------------------------'

结果

len of li == 24

sea             mountain    desert  
Emma            Cathy       Kate    
HH              VVVVVVV     AAA     
round           flat        sharp   
nut             banana      apple   
heeeeeeeeeeen   tiger       snakered
purple          white       atlantic
pacific         antarctic   Bellini 

-----------------------------------------------------------
sea         mountain    desert      Emma         
Cathy       Kate        HH          VVVVVVV      
AAA         round       flat        sharp        
nut         banana      apple       heeeeeeeeeeen
tiger       snakered    purple      white        
atlantic    pacific     antarctic   Bellini      

-----------------------------------------------------------
sea             mountain    desert      Emma    Cathy
Kate            HH          VVVVVVV     AAA     round
flat            sharp       nut         banana  apple
heeeeeeeeeeen   tiger       snakered    purple  white
atlantic        pacific     antarctic   Bellini

-----------------------------------------------------------
sea     mountain    desert      Emma            Cathy       Kate    
HH      VVVVVVV     AAA         round           flat        sharp   
nut     banana      apple       heeeeeeeeeeen   tiger       snakered
purple  white       atlantic    pacific         antarctic   Bellini 

-----------------------------------------------------------
sea     mountain        desert  Emma        Cathy   Kate    HH      
VVVVVVV AAA             round   flat        sharp   nut     banana  
apple   heeeeeeeeeeen   tiger   snakered    purple  white   atlantic
pacific antarctic       Bellini

-----------------------------------------------------------

.

但我更喜欢列之间没有制表符的显示,但只有给定数量的字符。
在下面的代码中,我选择用 2 个字符分隔列:它是行中的 2

maxel = tuple(max(imap(len,islice(li,st,None,nc)))+2

编码

from itertools import imap,islice

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'heeeeeeeeeeen','tiger','snake'
      'red','purple','white',
      'atlantic','pacific','antarctic',
      'Bellini']

print 'len of li == %d\n' % len(li)
def cols_print(li,nc):
    maxel = tuple(max(imap(len,islice(li,st,None,nc)))+2
                  for st in xrange(nc))

    nblines,tail = divmod(len(li),nc)
    stakes = nc*['%%-%ds']
    form = ''.join(stakes) % maxel

    itn = iter(li).next

    print '\n'.join(form % tuple(itn() for g in xrange(nc))
                  for i in xrange(nblines)) 
    if tail:
        print ''.join(stakes[nc-tail:]) % maxel[0:tail] % tuple(li[-tail:]) + '\n'
    else:
        print


for nc in xrange(3,8):
    cols_print(li,nc)
    print 'mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm'

结果

len of li == 24

sea            mountain   desert    
Emma           Cathy      Kate      
HH             VVVVVVV    AAA       
round          flat       sharp     
nut            banana     apple     
heeeeeeeeeeen  tiger      snakered  
purple         white      atlantic  
pacific        antarctic  Bellini   

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea       mountain  desert     Emma           
Cathy     Kate      HH         VVVVVVV        
AAA       round     flat       sharp          
nut       banana    apple      heeeeeeeeeeen  
tiger     snakered  purple     white          
atlantic  pacific   antarctic  Bellini        

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea            mountain  desert     Emma     Cathy  
Kate           HH        VVVVVVV    AAA      round  
flat           sharp     nut        banana   apple  
heeeeeeeeeeen  tiger     snakered   purple   white  
atlantic       pacific   antarctic  Bellini  

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea     mountain  desert    Emma           Cathy      Kate      
HH      VVVVVVV   AAA       round          flat       sharp     
nut     banana    apple     heeeeeeeeeeen  tiger      snakered  
purple  white     atlantic  pacific        antarctic  Bellini   

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea      mountain       desert   Emma      Cathy   Kate   HH        
VVVVVVV  AAA            round    flat      sharp   nut    banana    
apple    heeeeeeeeeeen  tiger    snakered  purple  white  atlantic  
pacific  antarctic      Bellini  

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
于 2012-12-01T02:36:48.660 回答
2

这应该这样做:

In [12]: L
Out[12]: ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']

In [13]: for i in range(0,len(L),3): print ' '.join(L[i:i+3])
name1 name2 name3
name4 name5 name6

编辑:将所有内容都设置为固定宽度(我写了一段时间将列式数据转换为表格的一些代码。您所要做的就是对数据进行列化并调用此旧代码):

def tabularize(infilepath, outfilepath, delim='\t', largeFile=False):
        """ Return nothing
                Write into the file in outfilepath, the contents of infilepath, expressed in tabular form.
                The tabular form is similar to the way in which SQL tables are displayed.
                If largeFile is set to True, then no caching of lines occurs. However, two passes of the infile are required"""

        if largeFile:
                widths = getWidths(infilepath, delim)
        else:
                with open(infilepath) as infile:
                        lines = [line.strip().split(delim) for line in infile.readlines() if line.strip()]
                widths = [max([len(row) for row in rows])+2 for rows in izip_longest(*lines, fillvalue="")]

                with open(outfilepath, 'w') as outfile:
                        outfile.write("+")
                        for width in widths:
                                outfile.write('-'*width + "+")
                        outfile.write('\n')
                        for line in lines:
                                outfile.write("|")
                                for col,width in izip_longest(line,widths, fillvalue=""):
                                        outfile.write("%s%s%s|" %(' '*((width-len(col))/2), col, ' '*((width+1-len(col))/2)))
                                outfile.write('\n+')
                                for width in widths:
                                        outfile.write('-'*width + "+")
                                outfile.write('\n')

def getWidths(infilepath, delim):
        answer = defaultdict(int)
        with open(infilepath) as infile:
                for line in infile:
                        cols = line.strip().split(delim)
                        lens = map(len, cols)
                        for i,l in enumerate(lens):
                                if answer[i] < l:
                                        answer[i] = l

        return [answer[k] for k in sorted(answer)]

def main(L, n, infilepath, outfilepath):
    iterator = iter(L)
    with open(infilepath, 'w') as infile:
        for row in itertools.izip_longest([iterator]*n, fillavalue=''):
            infile.write('\t'.join(row)+'\n')
    if len(L) > 10**6:
        largeFile = True
    tabularize(infilepath, outfilepath, delim='\t', largeFile)
于 2012-12-01T00:32:26.043 回答
2

你也可以试试这个:

from itertools import izip

l = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']

for t in izip(*[iter(l)]*3):
    print '\t'.join(t)
名称1 名称2 名称3
名字4 名字5 名字6

如果您不确定列表长度是否为 3 的倍数,您可以使用izip_longest,应用相同的想法:

from itertools import izip_longest as izipl

l = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7']

for t in izipl(fillvalue='', *[iter(l)]*3):
    print '\t'.join(t)
名称1 名称2 名称3
名字4 名字5 名字6
名称7   
于 2012-12-01T00:37:21.680 回答
1

尝试使用itertools我认为它更简单的解决方案。

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

names = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']
for item1 in grouper(3, names, ''):
    print '\t'.join(item1)

结果:

name1   name2   name3
name4   name5   name6
于 2012-12-01T00:35:36.003 回答