2

私は107の名前のリストを持っていますが、3つ程度のグループでそれらを印刷したいと思います。各名前はタブで区切られ、各行の後に改行が最後まであります。これどうやってするの?

もちろん、1行に1つのfor item in list print item名前しか表示されません。これは問題ありませんが、一度にコンソールにもっと収まりたいので、リストを確認しながら、各行に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)

必要な数の列に一般化するために、アルゴリズムを変更しました。
必要な列数を引数としてパラメーターに渡す必要があります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)
name1 name2 name3
name4 name5 name6

リストの長さが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)
name1 name2 name3
name4 name5 name6
name7   
于 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 に答える