【问题标题】:Print python list in groups of 3以 3 个为一组打印 python 列表
【发布时间】:2012-11-19 06:11:39
【问题描述】:

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

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

name1
name2
name3
name4
name5
name6

我会得到:

name1     name2     name3
name4     name5     name6

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

[edit:update] 使用@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

我怎样才能把它清理干净,以便每列中的所有内容都很好地对齐?我想要做的事情容易吗?

【问题讨论】:

标签: python list printing tabs iteration


【解决方案1】:

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)

我已经修改了算法,以便泛化到所需的任意数量的列。
需要的列数必须作为参数传递给参数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

【讨论】:

  • 哦,天哪,这看起来正是我想要的,非常感谢你:) 蛋糕送给你
  • 有什么办法可以让它变成 5 列而不是 3 列?我尝试更改一些数字,添加另一个元素定义,并修复字符串格式,但它出错了
  • 我想我想通了,我现在打印了 5 个,宽度仅略低于 80 个字符,这很好,谢谢您的帮助 :)
  • 我似乎发现了这个方法的一个bug,在某些情况下,如果我的名字列表的长度发生了变化,最后一些不会被打印出来,我认为它有一些东西要用 divmod 正在做的数学。有什么办法吗?
  • @Kassandra 我会检查问题,但请您再描述一下好吗?
【解决方案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

【讨论】:

  • 这很简洁但令人困惑!
【解决方案3】:

应该这样做:

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)

【讨论】:

  • 这确实做到了,虽然它不是我想的干净对齐,我的名字有不同的长度,有些在一个列中对齐,其他不是,有什么办法得到这是为了确保事物像表格一样对齐?
  • 哦,天哪,这比我想的要复杂,哈哈,谢谢你提供的大代码,我试试看。
【解决方案4】:

尝试使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多