2017-03-02 62 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的數據結構,比如列表,特別是列表解析,地圖,lambda表達式,*運算符等等。你可以看到我在我的答案中使用了很多並且總是儘可能使代碼儘可能爲'pythonic':-P

此外,當迭代列表總是使用for a in arr:for i,a in enumerate(arr)而不是i in range()時。它看起來好多了

+0

爲什麼-1?我的代碼也適用。 –