2017-03-02 40 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?我的代码也适用。 –