【问题标题】:Automate the Boring Stuff Chapter 6 Table Printer Almost Done自动化无聊的东西第 6 章台式打印机几乎完成
【发布时间】:2016-04-01 23:36:34
【问题描述】:

在本节中,他们希望我们创建此表:

    apples Alice dogs
     oranges Bob cats
 cherries Carol moose
   banana David goose

必须右对齐,输入为tableData。这是我的代码:

tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]
listlens=[]
tour=0
lists={}
for m in tableData:
    total=0
    tour+=1
    for n in m:
        total+=len(n)
        lists["list:",tour]=total
    print("list",tour,total)    

itemcount=list(lists.values())
sortedlen=(sorted(itemcount,reverse=True))
longest=sortedlen[0]

#print (lists['list:', 1])
#print (longest)


for m in range(len(tableData[0])):
    for n in range(len(tableData)):
        print (tableData[n][m],end=" ")
        n+=1
    print ("".rjust(lists['list:', 1],"-"))
    m+=1

我几乎完成了,除了一件事,我不能让它正确。这个输出是我迄今为止最接近的输出。

apples Alice dogs ---------------------------
oranges Bob cats ---------------------------
cherries Carol moose ---------------------------
banana David goose ---------------------------

如果我将 rjust 放在内部 for 循环中,则输出会大不相同:

apples-------------------------- Alice-------------------------- dogs-------------------------- 
oranges-------------------------- Bob-------------------------- cats-------------------------- 
cherries-------------------------- Carol-------------------------- moose-------------------------- 
banana-------------------------- David-------------------------- goose-------------------------- 

【问题讨论】:

  • 你尝试过先加入吗?
  • 你能再解释一下吗?你的意思是在 print 函数的末尾还是在 for 循环中?
  • 我现在试过了,但是参数错误。

标签: python python-3.x printing


【解决方案1】:
W = 3
H = 4
def printTable(table):
    colWidth = []
    for i in range(W):
        r =[]
        for j in range(H):
            count = len(table[i][j])
            r.append(count)
        colWidth.append(r)
    right = []
    for i in range(len(colWidth)):
        m = max(colWidth[i])
        right.append(m)
    for j in range(H):
        for i in range(W):
            print(table[i][j].rjust(right[i]), end = ' ')
        print()
tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
    

【讨论】:

    【解决方案2】:

    我就是这样做的,不确定这是否是最佳答案,但最受好评的答案无法正常工作:

    tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]
    
    
    def printTable(table):
        colWidths = [0] * len(table)
    
        for i in range(len(table)): #for each list
            for j in range(len(table[i])): #for each word in the list
                if(len(table[i][j]) > colWidths[i]): #if longest word
                    colWidths[i] = len(table[i][j]) #store new max len
    
        for n in range(len(table[0])): # for len of each list (same size in spec)
            for m in range(len(table)):
                print(table[m][n].rjust(colWidths[m]), end=" ") # print each column 
            print('', end='\n')
        
    
    printTable(tableData)
    

    【讨论】:

      【解决方案3】:

      所以,我知道这是一个旧答案,但有些人刚刚开始学习 python,这本书太棒了!这是我的回答,我觉得比别人写的简单一点:

      #! Python 3
      #Table printer
      
      tableData = [['apples', 'oranges', 'cherries', 'banana'],
      ['Alice', 'Bob', 'Carol', 'David'],
      ['dogs', 'cats', 'moose', 'goose']]
      
      def Tableprinter(tableData):
          listademax=[]
          for i in range(len(tableData)):
              listademax.append(len(max(tableData[i],key=len)))
          elmax=int(max(listademax))
          for m in range(len(tableData[0])):
              for n in range(len(tableData)):
                  print(tableData[n][m].rjust(elmax),end=' ')
              print()
      
      Tableprinter(tableData)
      

      【讨论】:

        【解决方案4】:

        为了更加动态,我用 Python 3 编写了脚本。

        tableData = [['apples', 'oranges', 'cherries', 'banana', 'dragonfruit'],
                     ['Alice', 'Bob', 'Carol', 'David', 'Steve'],
                     ['dogs', 'cats', 'moose', 'goose', 'lioness']]
        
        """
             apples Alice    dogs
            oranges   Bob    cats
           cherries Carol   moose
             banana David   goose
        dragonfruit Steve lioness
        """
        
        results = []
        final = []
        list_length = 0
        elements_length = 0
        long_str = {}
        
        
        def printTable(tableData, list_length):
        
            # Get the max elements which exists inside list of list
            for elements in tableData:
                if list_length != len(elements):
                    list_length = len(elements)
        
            # To create keys to store the maximum length of string in the list of ist
            for i, names in enumerate(tableData):
                col = 'col'
                col = col + str(i+1)
                max_length = 0
                for name in names:
                    if len(name) > max_length:
                        max_length = len(name)
                        long_str[col] = max_length
                    else:
                        pass
        
            # To gather the elements across multiple lists based on their index value
            for iteration in range(list_length):
                initial_list = []
                for element in tableData:
                    initial_list.append(element[iteration])
                results.insert(iteration, initial_list)
        
            # To right adjust all the elements in the list of list
            for i, result in enumerate(results):
                indent_list = []
                for index in range(len(result)):
                    col_no = 'col' + str(index+1)
                    indent_list.append(result[index].rjust(long_str[col_no]))
                final.insert(i, indent_list)
        
            # To get the string like output
            for final_element in final:
                print(' '.join(final_element))
        
        printTable(tableData, list_length)

        【讨论】:

          【解决方案5】:

          我的解决方案如下。

          tableData = [['apples', 'oranges', 'cherries', 'banana'],
                       ['Alice', 'Bob', 'Carol', 'David'],
                       ['dogs', 'cats', 'moose', 'goose']]
          
          def printTable(tableData):
          
              finalList = []
          
              for i in range (0, 4):
          
                  #iterate through each list in tableData    
                  for lists in tableData:             
          
                      #value of longest string in each list       
                      longestValue = len(max(lists, key=len))
          
                      #add each value list0[0], list1[0], etc. to finalList...             
                      #width = longestValue  
                      finalList += lists[i].rjust(longestValue) + "  "
          
                      #skip to new line at end of sequence
                      finalList += '\n'   
          
              #join list into a string for output    
              s = ''
              finalList = s.join(finalList) 
          
              #return final list as a formatted string
              print(finalList)                                            
          
          printTable(tableData)
          

          【讨论】:

          • 请解释这与其他提供的答案有何不同。
          【解决方案6】:
          # table printer
          def printtable(tabledata,columnwidth):
              for y in range(4):
                  print()
                  for x in range(len(tabledata)):
                      print(tabledata[x][y].rjust(columnwidth),end='')
              tabledata=[['apples','oranges','cherries','banana'],. 
               ['Alice','Bob','Carol','David'],
               ['dogs','cats','moose','goose']]
              n=len(tabledata[0][0]
              for y in range(4):
                  for x in range(len(tabledata)):
                      if len(tabledata[0][0])>=len(tabledata[x][y]):
                         False
                     else:
                         n=len(tabledata[x][y])
              printtable(tabledata,n)
          

          【讨论】:

          • 欢迎堆栈溢出。还请添加关于代码功能的描述,而不仅仅是提供代码。
          【解决方案7】:

          这是我找到的满足目标的最简单方法。这是我的代码:

          tableData = [['apples', 'oranges', 'cherries', 'banana'],
                       ['Alice', 'Bob', 'Carol', 'David'],
                       ['dogs', 'cats', 'moose', 'goose']]
          
          def printTable(myTable):
          
              #each column is a different width, so colWidth is a list which contains the width of each column
              #this is also suggested in the problem itself
              colWidth=[0]*len(myTable)
              for x in range(len(myTable)):
                  for item in myTable[x]:
                      if len(item)>colWidth[x]:
                          colWidth[x]=len(item)
          
              #printing the table is similar to the exercise at the end of Chapter 4
              for a in range (len(myTable[0])):
                  for b in range (len(myTable)):
                      print (str(myTable[b][a]).rjust(colWidth[b]), end = ' ')
                  print('\n')
          
          printTable(tableData)
          

          【讨论】:

            【解决方案8】:

            我知道这已经有好几年了,但我几周前开始阅读这本书,这就是我发现那本书的方法:'D

            tableData = [['apples', 'oranges', 'cherries', 'banana'], 
                         ['Alice', 'Bob', 'Carol', 'David'], 
                         ['dogs', 'cats', 'moose', 'goose']]
            n=0
            x=''
            colWidths=[0]*len(tableData)
            
            for i in range(len(tableData)):
                for n in range(len(tableData[0])-1):
                    if colWidths[i]<len(tableData[i][n])+1:
                        colWidths[i]=len(tableData[i][n])+1
            
            for n in range(len(tableData[n])):
                x=''
                for i in range(len(tableData)):
                    x+=str(tableData[i][n]).rjust(colWidths[i])
            
                print(x)
            

            【讨论】:

              【解决方案9】:

              我的解决方案:

              tableData = [['apples', 'oranges', 'cherries', 'banana'],
                       ['Alice', 'Bob', 'Carol', 'David'],
                       ['dogs', 'cats', 'moose', 'goose']]
              
              
              def printTable(table):
              liste = 0
              colWidths = [0] * len(tableData)
              for lister in table:
                  liste = liste +1
                  longest =0
                  for strenge in lister:
                      if len(strenge) > longest:
                          longest = len(strenge)
                  colWidths.insert((liste-1),longest)
              
              for i in range(len(lister)):
                  print()
                  for lister in table:
                      print (lister[i].rjust(colWidths[0]),end='')
              
              printTable(tableData)
              

              【讨论】:

                【解决方案10】:

                如果你按照这本书来,我想这就是答案。包括提示和您迄今为止所学的内容。

                tableData = [['apples', 'oranges', 'cherries', 'banana'],
                             ['Alice', 'Bob', 'Carol', 'David'],
                             ['dogs', 'cats', 'moose', 'goose']]
                

                创建函数'printTable'。首先是获取 3 个列表中最长的 3 个字符串的长度,并将整数值放入 de list 'colWidths'

                def printTable(table):
                    colWidths = [0] * len(table) # The tip from the book
                    for i in range(len(table)):
                        for s in range(len(table[i])):
                            l = len(table[i][s]) # get the length of the individual strings
                            if colWidths[i] < l: # check wich one is the longest
                                colWidths[i] = l # save the value in the list
                

                函数的下一部分是从列表中的项目中获取正确的列。我在这部分遇到了一些麻烦,但最终我得到了它。

                    for x in range(len(table[0])):
                        for y in range(len(table)):
                            if y == len(table) - 1:
                                print(table[y][x].rjust(colWidths[y], ' '))
                            else:
                                print(table[y][x].rjust(colWidths[y], ' '), end=' ')
                

                执行函数:

                printTable(tableData)
                

                【讨论】:

                  【解决方案11】:

                  很高兴看到每个人的做法都不同,但仍然得到相同的结果。我是这样做的:

                  tableData = [['apples', 'oranges', 'cherries', 'banana'],
                               ['Alice', 'Bob', 'Carol', 'David'],
                               ['dogs', 'cats', 'moose', 'goose']]
                  
                  def printTable(table):
                      table_len = []
                      max_of_table = []
                      next_item = ''
                      for i in range(len(table)):
                          temp_len = []
                          for k in range(len(table[i])):
                              temp_len.append(len(table[i][k]))
                          table_len.append(temp_len)
                      for b in table_len:
                          max_of_table.append(max(b))
                      for a in range(len(table[0])):
                          for s in range(len(table)):
                              next_item = str(table[s][a])
                              next_item = next_item.rjust(max_of_table[s])
                              print(next_item, end=' ')
                          print('')
                  
                  printTable(tableData)
                  

                  【讨论】:

                    【解决方案12】:

                    这么多不同的解决方案!这本书教我们每个范围(len(x)),我在网上读到这不是获取索引的好方法。一个更好的建议解决方案是我在代码中使用的枚举,您可以在此处找到更多信息:

                    https://python-forum.io/Thread-Basic-Never-use-for-i-in-range-len-sequence

                    #! python3
                    # printTable.py - Displays a list in a well organized table
                    
                    tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                 ['Alice', 'Bob', 'Carol', 'David'],
                                 ['dogs', 'cats', 'moose', 'goose']]
                    columnWidth = [] # Creates a empty list
                    
                    def printtable(printdata):
                        for data in printdata:
                            # Adds the length of the longest string to the columnWidth list
                            columnWidth.append(len(max(data, key=len))) 
                        # For loop to decide the determine the number of columns to cycle through
                        for x, columnData in enumerate(printdata[0]): 
                            # For loop for the number of rows to cycle through
                            for y, rowData in enumerate(printdata): 
                                # Print each row data with the correct justification
                                print(printdata[y][x].rjust(columnWidth[y]), end=' ')
                            # Create a new line before reiterating
                            print('') 
                    
                    printtable(tableData)
                    

                    【讨论】:

                    【解决方案13】:

                    我是这样做的,使用了目前书中使用的提示和唯一信息。

                    无论 tableData 中有多少子列表,也无论每个子列表中有多少项目,此代码都有效。

                    我在循环中使用了一个循环来实现这一点,并在每个打印项目之后打印一个空格。如果是最后一个类别项,则打印一个新行。

                    tableData = [['apples', 'oranges', 'cherries', 'banana','orange'],
                                 ['Alice', 'Bob', 'Carol', 'David','Phillip'],
                                 ['dogs', 'cats', 'moose', 'goose','anteater'],
                                 ['mitsubishi','honda','toyota','ford','range rover']]
                    
                    
                    def printTable(table):
                        colWidths = [0] * len(table)
                        for i in range(len(table)):
                            for x in table[i]:
                                if len(x) > colWidths[i]:
                                    colWidths[i] = len(x)
                        print(colWidths)
                    
                        for i in range(len(table[0])):
                            for x in range(len(table)):
                                print(table[x][i].rjust(colWidths[x]),end = ' ')
                                if x == len(table)-1:
                                    print('\r')
                    
                    
                    
                    printTable(tableData)
                    
                    
                    '''
                    table[0,0] + table [1,0] + table [2,0]
                    table[1,0] + table [1,1]
                    
                    '''
                    

                    【讨论】:

                      【解决方案14】:

                      我就是这样做的。

                      对于代码的第一部分,我只是使用了他们给我们的提示。

                      第 4 章 / 实践项目 / 角色图片网格中,我们学习了如何“旋转”然后打印列表列表.它对我的代码的第二部分很有用。

                      #!/usr/bin/python3
                      # you can think of x and y as coordinates
                      
                      tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                   ['Alice', 'Bob', 'Carol', 'David'],
                                   ['dogs', 'cats', 'moose', 'goose']]
                      
                      def printTable(table):
                          # create a new list of 3 "0" values: one for each list in tableData
                          colWidths = [0] * len(table)
                          # search for the longest string in each list of tableData
                          # and put the numbers of characters in the new list
                          for y in range(len(table)):
                              for x in table[y]:
                                  if colWidths[y] < len(x):
                                      colWidths[y] = len(x)
                      
                          # "rotate" and print the list of lists
                          for x in range(len(table[0])) :
                              for y in range(len(table)) :
                                  print(table[y][x].rjust(colWidths[y]), end = ' ')
                              print()
                              x += 1
                      
                      printTable(tableData)
                      

                      【讨论】:

                      • 谢谢!我的解决方案让我摸不着头脑。据我所知,'x += 1' 是不必要的
                      【解决方案15】:
                      def table_print(tabledata):
                          column=[0]*len(tabledata)
                          for k in  range(len(tabledata)):
                              column[k]=len(max(tabledata[k],key=len))
                      
                          for i in range(len(tabledata[0])):
                              for j in range(len(tabledata)):
                                  print(tabledata[j][i].rjust(column[j]+1),end="")
                              print()
                          return
                      table_Data = [['app', 'oranges', 'cherries', 'banana'],
                      ['Ale', 'Bob', 'Crol', 'Dad'],
                      ['dogs', 'cats', 'moose', 'ge']]
                      table_print(table_Data)
                      

                      【讨论】:

                      • 欢迎来到 SO。我相信您可以在代码中添加一些描述和陷阱,以获得更好的答案。
                      【解决方案16】:

                      这是我解决这个问题的方法。

                      tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                   ['Alice', 'Bob', 'Carol', 'David'],
                                   ['dogs', 'cats', 'moose', 'goose']]
                      
                      
                      def printTable(mylist):
                        #getting the item who has the max length in the inner tables
                        maxLength = 0
                        for item in mylist:
                          for i in item:
                            if len(i) > maxLength:
                              maxLength = len(i)
                            else:
                              maxLength = maxLength
                        # make a seperated rjust for every item in the inner lists
                        for item in mylist:
                          for i in range(len(item)):
                            item[i] = (item[i].rjust(maxLength))
                        # convert list to dictionary data type it's more easier to deal with.
                        myNewlist = {0: [], 1: [], 2: [], 3: []}
                        for i in range(len(item)):
                          for u in tableData:
                            myNewlist[i].append(u[i])
                        # print the out put :) 
                        for key, value in myNewlist.items():
                          print(''.join(value))
                      
                      
                      (printTable(tableData))
                      

                      【讨论】:

                        【解决方案17】:

                        这里,首先我们要计算每个内部列表中最长字符串的长度,我们将其存储在“colWidths”列表中。之后,我们将简单地遍历“tableData”列表。但是在打印时,我们需要通过该字符串的最大列宽(即存储在 colwidth 中)对每个字符串进行右对齐,以便保持对称性。否则只是打印。

                        tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                     ['Alice', 'Bob', 'Carol', 'David'],
                                     ['dogs', 'cats', 'moose', 'goose']]
                        
                        def printTable(t):
                            colWidths=[0] * len(tableData)
                            l=[]
                            for j in range(len(t)):
                                for i in t[j]:
                                    l+=[len(i)]
                                colWidths[j]= max(l)
                                l=[]
                            print(colWidths)
                        
                            for j in range(len(t[0])):
                                for i in range(len(t)):
                                    print(t[i][j].rjust(colWidths[i]),end=' ')
                                print(end='\n')
                        
                        printTable(tableData)
                        

                        【讨论】:

                          【解决方案18】:
                          tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                  ['Alice', 'Bob', 'Carol', 'David'],
                                  ['dogs', 'cats', 'moose', 'goose']]
                          
                          
                          
                          def find_max_length(item_list):
                              #find the length of the "item_list" parameter
                              colWidth = [0] * len(item_list)
                          
                               #an empty list created to hold a single inner list from the                             #"item_list" parameter
                               not_so_emptylist = []
                          
                              i = 0
                              maxlength = 0 #variable to hold max length of an item in the inner list  
                          
                              for i in range(len(item_list)):
                                  not_so_emptylist = item_list[i]
                                  for item in not_so_emptylist:
                                      if len(item) > maxlength:
                                          maxlength = len(item)
                                  colWidth[i] = maxlength
                                  maxlength = 0
                          
                              return colWidth 
                          
                          #an empty list to pass colwidth to
                          width = []
                          
                          def print_table_data(a_list):
                              width = find_max_length(a_list)
                          
                              i = 0
                          
                              for i in range(4):
                                  print(a_list[0][i].rjust(width[0]) + ' ' + a_list[1][i].rjust(width[1]) + ' ' + a_list[2][i].rjust(width[2]))
                          
                          print_table_data(a_list=tableData)
                          

                          【讨论】:

                          • 解释你的解决方案真的很有帮助。
                          【解决方案19】:

                          也许不是最好的方法,但这是我的任务解决方案:

                          def printtable(listlist):
                              # variable stores the maximum length of the words in the lists
                              lenghtCounter = 0  #8
                              listCounter = 0  #3
                              dict = {}
                          
                              for list in listlist:
                                  listCounter += 1
                                  wordcounter = 0  
                          
                                  for pos in range(len(list)):
                                      wordcounter += 1
                          
                                      for word in list[pos:len(list):len(list)]:
                                          dict.update({list[pos]: pos})
                          
                                          # length counter will store the longest value
                                          if len(word) > lenghtCounter:
                                              lenghtCounter = len(word)
                          
                              for i in range(wordcounter):
                                  line = []
                                  strline = ''
                          
                                  for k, v in dict.items():
                                      if v == i:
                                          line.append(k)
                                          strline.join(k.ljust(lenghtCounter))
                          
                                  for el in line:
                                      strline += el.ljust(lenghtCounter + 5)
                                  print(strline)
                          
                          tableData = [
                              ['apples', 'oranges', 'cherries', 'bananas'],
                              ['Alice', 'Bob', 'Carol', 'David'],
                              ['dogs', 'cats', 'moose', 'goose']
                          ]
                          
                          printtable(tableData)
                          

                          【讨论】:

                            【解决方案20】:
                            def print_table(tab):
                                for j in range(len(tab[0])):
                                    for i in range(len(tab)):
                                        m = max([len(s) for s in tab[i]])
                                        print(tab[i][j].rjust(m), end=' ')
                                    print('')
                            
                            
                            tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                         ['Alice', 'Bob', 'Carol', 'David'],
                                         ['dogs', 'cats', 'moose', 'goose']]
                            
                            print_table(tableData)
                            

                            【讨论】:

                              【解决方案21】:

                              这是我的练习方法:

                              #!/usr/bin/env python3
                              
                              tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                           ['Alice', 'Bob', 'Carol', 'David'],
                                           ['dogs', 'cats', 'moose','goose']]
                              
                              def printTable():
                                  colWidths = [0] * len(tableData)
                              
                                  # find longest word in each list, convert to int
                                  # and add to colWidths var
                                  for i in range(len(tableData)):
                                      for l in tableData[i]:
                                          if len(l) >= colWidths[i]:
                                              colWidths[i] = len(l)
                                  # print and justify using the values from colWidths + 1
                                  for t in range(4):
                                      print(tableData[0][t].rjust(colWidths[0]+1) + \
                                            tableData[1][t].rjust(colWidths[1]+1) + \
                                            tableData[2][t].rjust(colWidths[2]+1))
                              
                              printTable()
                              

                              【讨论】:

                                【解决方案22】:

                                我认为最简单的解决方案是在整个列表(内部和外部)中找到最大大小字符串的长度,然后将其设置为右对齐方法(rjust())的参数,然后使用循环来打印列表值根据问题。

                                tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                             ['Alice', 'Bob', 'Carol', 'David'],
                                             ['dogs', 'cats', 'moose', 'goose']]
                                
                                
                                innerlen=0
                                
                                for m in tableData:
                                    for n in m:
                                        if innerlen < len(n):
                                            innerlen = len(n)
                                
                                
                                
                                
                                for m in range(len(tableData[0])):
                                    for n in range(len(tableData)):
                                        print(tableData[n][m].rjust(innerlen),end="")
                                
                                    print("")
                                

                                【讨论】:

                                  【解决方案23】:
                                  tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                              ['Alice', 'Bob', 'Carol', 'David'],
                                              ['dogs', 'cats', 'moose', 'goose']]
                                  
                                  def printTable(list):
                                      len_list = []
                                      for i in range(len(list)):
                                          len_list.append(len(max(list[i], key=len)))
                                      for m in range(len(list[i])):
                                          for i in range(len(list)):
                                              print(list[i][m].rjust(len_list[i]+1), end = "")
                                          print() #to add a new line
                                  
                                  printTable(tableData)
                                  

                                  【讨论】:

                                    【解决方案24】:
                                    tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                             ['Alice', 'Bob', 'Carol', 'David'],
                                             ['dogs', 'cats', 'moose', 'goose']]
                                    
                                    
                                    
                                    def printTable():
                                     #List colWidth contains the longest string in each of the inner lists
                                     colWidth=[0]*len(tableData)
                                    
                                     n=0
                                     #To find the longest string in each of the inner lists and store in 
                                      colWidth
                                     for li in tableData:
                                        num=0
                                        for j in li:
                                            if(num<len(j)):
                                                num=len(j)
                                        colWidth[n]=num
                                        n=n+1
                                    
                                    #To find the largest value in the colWidths list to find out what integer 
                                     width to pass to the rjust() string method.
                                     c=0
                                     for i in colWidth:
                                        if(c<i):
                                            c=i
                                    
                                    #To print the data
                                     for m in range(len(tableData[0])):
                                        for n in range(len(tableData)):
                                            print (tableData[n][m]).rjust(c),
                                        print('')
                                    
                                    printTable()
                                    

                                    【讨论】:

                                      【解决方案25】:

                                      所以这就是我最终的结果......没有太多的互联网帮助。然而,那条打印线很糟糕。我喜欢上面的一些,但不打算模仿。

                                      tableData = [['apples','oranges','cherries','banana'],
                                                   ['Alice','Bob','Carol','David'],
                                                   ['dogs','cats','moose','goose']]
                                      
                                      def printTable():
                                          colWidths=[0]*len(tableData)
                                          for i in range(len(tableData)):
                                              for x in range(len(tableData[i])):
                                                  if colWidths[i]<len(tableData[i][x]):
                                                      colWidths[i]=len(tableData[i][x])
                                          for x in range(len(tableData[i])):
                                              print(tableData[0][x].rjust(colWidths[0]+1) + tableData[1][x].rjust(colWidths[1]+1) + tableData[2][x].rjust(colWidths[2]+1))
                                      
                                      printTable()
                                      

                                      打印出来的结果是正确的,但我不喜欢它不允许动态使用的方式。回到打印线上的绘图板。

                                      【讨论】:

                                        【解决方案26】:

                                        根据作者的提示:

                                        "提示:您的代码首先必须在每个内部列表中找到最长的字符串,以便整个列的宽度足以容纳所有字符串。您可以将每列的最大宽度存储为整数。printTable() 函数可以以 colWidths = [0] * len(tableData) 开头,这将创建一个包含与 tableData 中的内部列表数量相同数量的 0 值的列表。这样,colWidths[0] 可以将最长字符串的宽度存储在tableData[0]中,colWidths[1]可以将最长字符串的宽度存储在tableData[1]中,依此类推。然后你可以在colWidths列表中找到最大值来找出什么要传递给 rjust() 字符串方法的整数宽度。"

                                        这是我的答案:

                                        tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                                     ['Alice', 'Bob', 'Carol', 'David'],
                                                     ['dogs', 'cats', 'moose', 'goose']]
                                        
                                        
                                        def table_printer(tab_data):
                                            col_widths = [0] * len(tab_data)  # creates 3 lists based on the list length
                                            for j in range(len(tab_data[0])):  # finds a length of 4 items (aka rows)
                                                for i in range(len(tab_data)):  # finds a length of 3 items (aka columns)
                                                    col_widths[i] = len((max(tab_data[i], key=len)))  # sets the column width to the maximum length of an item in the list
                                                    a = tab_data[i][j]
                                                    print(a.rjust(col_widths[i]), end=" ")  #  every time we print a column, we rjust it to the max width.
                                                print("\n")
                                        
                                        
                                        table_printer(tableData)
                                        

                                        【讨论】:

                                          【解决方案27】:
                                          #! python3
                                          #table printer prints takes a list of lists of strings and displays it in a
                                          #well-organized table with each column right-justified.
                                          
                                          tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                          ['Alice', 'Bob', 'Carol', 'David'],
                                          ['dogs', 'cats', 'moose', 'goose']]
                                          
                                          def printTable(data):
                                              #in this section we are creating a list containing each column's width
                                              colWidths = [0] * len(data)
                                              for m in range(len(colWidths)):
                                                  for n in range(len(data[0])):
                                                      if colWidths[m] < len(data[m][n]):
                                                         colWidths[m] =  len(data[m][n])
                                              #optionally you can also print colWidths for a better understanding 
                                              #print(colWidths) will output [8, 5, 5]
                                          
                                              #this section of the code helps arranging the list in a table format
                                              for u in range(len(data[0])):
                                                  for v in range(len(data)):
                                                      print(data[v][u].rjust(colWidths[v] + 1), end='')
                                                  print()
                                          
                                          printTable(tableData)
                                          

                                          【讨论】:

                                            【解决方案28】:

                                            这里有一个解决方案。即使内部列表的数量发生变化或内部列表中的元素数量发生变化,它也可以工作,因为所有内部列表都具有相同的元素数量。

                                            tableData = [
                                                ['apples', 'oranges', 'cherries', 'banana'],
                                                ['Alice', 'Bob', 'Carol', 'David'],
                                                ['dogs', 'cats', 'moose', 'goose']
                                            ]
                                            
                                            col_widths = list()
                                            for i, record in enumerate(tableData):
                                                col_widths.insert(i, max(len(item) for item in record))
                                            
                                            for i in range(len(tableData[0])):
                                                print(' '.join(record[i].rjust(col_widths[j]) for j, record in enumerate(tableData)))
                                            

                                            【讨论】:

                                            • 不错,简短而干净的答案!
                                            【解决方案29】:
                                            #! python3
                                            # Table Printer 1
                                            
                                            tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                                         ['Alice', 'Bob', 'Carol', 'David'],
                                                         ['dogs', 'cats', 'moose', 'goose']]
                                            
                                            def printTable(data):
                                                colWidths = [0] * len(data)
                                                for y in range(len(data[0])):
                                                    for x in range(len(data)):
                                                        colWidths[x] = len(max(data[x], key = len))
                                                        print(data[x][y].rjust(colWidths[x]), end = ' ')
                                                    print()
                                            
                                            printTable(tableData)
                                            
                                            
                                            #! python3
                                            # Table Printer 2
                                            
                                            tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                                         ['Alice', 'Bob', 'Carol', 'David'],
                                                         ['dogs', 'cats', 'moose', 'goose']]
                                            
                                            def printTable(data):
                                                colWidths = [0] * len(data)
                                                for x in range(len(data)):
                                                    for y in range(len(data[0])):
                                                        if len(data[x][y]) > colWidths[x]:
                                                            colWidths[x] = len(data[x][y])
                                                for y in range(len(data[0])):
                                                    for x in range(len(data)):
                                                        print(data[x][y].rjust(colWidths[x]), end = ' ')
                                                    print()
                                            
                                            printTable(tableData)
                                            

                                            【讨论】:

                                            • 嗨测试,你能发展你在这里做什么来回答这个问题吗?这绝对不清楚。
                                            【解决方案30】:

                                            我遇到了完全相反的问题:我已经想出了如何确定右对齐的参数,以及如何右对齐项目。然而,我很难在一行中打印多个项目。我尝试了“end=''”,但输出看起来仍然很奇怪。最终,我尝试将要打印的项目连接在一行中,并在循环中再调用一次打印函数。它奏效了。

                                            我花了几个小时来完成这个简单的练习,但绝对值得!:) 回顾所有增量改进最终如何使代码正常工作,感觉真的很好!

                                            这是我的代码。希望它会有所帮助。

                                            tableData = [['apples', 'oranges', 'cherries', 'banana'],
                                                         ['Alice', 'Bob', 'Carol', 'David'],
                                                         ['dogs', 'cats', 'moose', 'goose']]
                                            
                                            def printTable(tableData):
                                                colWidths = [0] * len(tableData)
                                                for i in range(len(tableData)):
                                                    for j in range(len(tableData[i])):
                                                        if colWidths[i] <= len(tableData[i][j]):
                                                            colWidths[i] = len(tableData[i][j])
                                                        else:
                                                            colWidths[i] = colWidths[i]
                                            
                                                for j in range(len(tableData[i])):
                                                    for i in range(len(tableData)):
                                                        print(''.join(tableData[i][j].rjust(colWidths[i] + 1)), end = '')
                                                        #the "+ 1" is used to allow for a space in between
                                                        print()
                                            
                                            printTable(tableData)
                                            

                                            顺便说一句,我很惊讶

                                            for j in range(len(tableData[i])):
                                                for i in range(len(tableData)):
                                            

                                            确实有效。

                                            在这种情况下,不应该总是在 j 之前使用 i 吗?这对我来说似乎违反直觉,但无论如何尝试它时它奇迹般地起作用。

                                            【讨论】:

                                              猜你喜欢
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 2019-10-09
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              • 1970-01-01
                                              相关资源
                                              最近更新 更多