Python print form

Quick Start Python programming practice project title, welcome to testify and optimization!
Write a function called printTable (), which accepts the list of lists of strings, it will be displayed in the group
organization good table, each column of a right-aligned. It assumed that all the inner list contains the same number of strings. For example,
the value may look like this:
TableData = [[ 'Apples', 'oranges', 'Cherries', 'Banana'],
[ 'Alice', 'Bob', 'Carol', 'David'],
[ 'dogs', 'cats', 'moose', 'goose']]
your printTable () function prints out:
Python print form
thinking a:
1. Compute the list (including a list of internal) length of the longest element;
2. most value of the long length of a printing element as a global list of values right justified
codes:

import copy
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob1111111111111', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def count_width(the_list):
    #定义函数:计算列表字符串最长值
    new_list=copy.deepcopy(the_list)
    #复制列表保存到独立的新列表
    colWidths = [0] * len(new_list)
    #创建一个列表,数目等同于tableData
    i=0
    while i < len(new_list):
        new_list[i].sort(key = lambda i:len(i),reverse = True)
        '''重新按照字符长度逆序(从大到小),lamba表示匿名函数,key = lambda i:len(i)代表
           以元素i的len()值作为比较
        '''
        colWidths[i]=new_list[i][0]
      #  print (colWidths[i])
        i=i+1
    #将tableData[i]降序排序,取最大值(第一个),得到一个每个内层列表中最长的字符串的列表
    colWidths.sort(key = lambda i:len(i),reverse = True)
    width=len(colWidths[0])
    #将colWidths降序排序,取最大值(第一个)并计算其字符宽度
    #print (width)
    #print (the_list)
    #print (new_list)
    return width

def list_rjust(the_list,width):
    for j in range (len(the_list[0])):
        for i in range (len(the_list)):
            print(the_list[i][j].rjust(width),end=" ")
        print("\r")
list_rjust(tableData,count_width(tableData))

Two ideas:
1. Compute the list (array, not nested arrays) the maximum value of the element;
2. Printing List element values in the list the longest (maximum value of each column may be different)
codes:

tableDate=[['apples', 'oranges', 'cherries', 'banana'],
           ['Alice', 'Bob', 'Carol', 'David'],
           ['dogs', 'cats', 'moose', 'goose']]
def findmaxlen(Dates):
    '''
    计算一个数组中最长元素的长度
    '''
    maxlen=0
    for i in range(len(Dates)):
        if len(Dates[i])>maxlen:
            maxlen=len(Dates[i])
    return maxlen
#print(findmaxlen(tableDate[0]))

def printTable(the_list):
    for j in range (len(the_list[0])):#打印内部数组的第j个
        for i in range (len(the_list)):#打印数组的第i个
            print(the_list[i][j].rjust(findmaxlen(the_list[i])),end=' ')
            #打印第i个数组的第j个内部数组时,按照第i个数组中的元素最长值右对齐
        print("\r")
printTable(tableDate)

Guess you like

Origin blog.51cto.com/xxy12345/2426612