2017-03-02 12 views
-3

私はこのコードが過度であるように感じます - どのように短くすることができますか?私は初心者ですので、私に同行してください。このコードをより効率的に書くにはどうすればよいですか?

The problem statement is this (from Automate the Boring stuff)

そして、私のコード:一般的に

#printtable() function - will take string list and display in rjustified table 

tabledata = [['apples', 'oranges', 'cherries', 'banana'], 
      ['Alice', 'Bob', 'Carol', 'David'], 
      ['dogs', 'cats', 'moose', 'goose']] 
def printtable(): 
    colwidths = [0] * len(tabledata) 
    strlen = 0 

#find parameter for rjust 

    for i in range(len(tabledata)): 
     for k in range(len(tabledata[i])): 
      wordlength = (len(tabledata[i][k])) 
      if wordlength > strlen: 
       colwidths[i] = wordlength 
      strlen = wordlength 
    maxword = max(colwidths) 

#print as table : 'invert' 
    x=0 
    while x<int(len(tabledata[0])): 
     for i in range(len(tabledata)): 
      print(tabledata[i][x].rjust(maxword, ' '), end=''), 
     x+=1 
     print('\n') 

printtable() 

、どのように私はより効率的にコーディングすることを学ぶために始めることができますか?私は先にフローチャートを書くことができると思っていました。通常、私はただ書くだけで、その場で物事を変え始めるからです。私のコードはすべて醜いと思うので、どんなヒントもありがとうございます。ありがとう!

+6

これはにあるはずです:http://codereview.stackexchange.com/ –

答えて

0
import six 

tabledata = [['apples', 'oranges', 'cherries', 'banana'], 
      ['Alice', 'Bob', 'Carol', 'David'], 
      ['dogs', 'cats', 'moose', 'goose']] 
def printtable(): 
    widths = [] 

    for row in tabledata: 
     widths.append(max(*map(len,row))) 

    inverted = map(list, six.moves.zip_longest(*tabledata, fillvalue=' ')) 

    for row in inverted: 
     for j,word in enumerate(row): 
      w = widths[j] 
      l = len(word) 
      print ' '*(w-l)+word+' ', 
     print 

ちょうど反転部分が減少しました。また、印刷 '' *(w-l)は右側のスペースです。また、ちょうど楽しみのためにここでいくつかの中心の整列をやってみることもできます。

また、あなたの質問に答えるためには、たくさんの練習をし、リストのようなすべてのpythonのデータ構造を理解する必要があります。特に、comprehensions、map、lambdas、* operatorなどをリストします。できるだけあなたのコードを「ピジョンソニック」にしようとしてください.-P

i in range()の代わりに、反復リストは常にfor a in arr:またはfor i,a in enumerate(arr)を使用します。それはもっと良く見える

+0

なぜ-1?私のコードも同様に動作します.. –

関連する問題