Python編程快速上手實踐項目題目,歡迎指證與優化!
編寫一個名爲 printTable()的函數, 它接受字符串的列表的列表,將它顯示在組
織良好的表格中, 每列右對齊。假定全部內層列表都包含一樣數目的字符串。例如,
該值可能看起來像這樣:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
你的 printTable()函數將打印出:
思路一:
1.計算列表中(包括內部列表)最長元素的長度;
2.以最長元素的長度值做爲全局右對齊的值打印列表
代碼:編程
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))
思路二:
1.計算列表(數組,沒有嵌套數組)最長元素的值;
2.按照列表最長元素的值打印列表(每列的最長值可能不一樣)
代碼:數組
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)