Python:テーブルプリンター



Python Table Printer



「Pythonプログラミングクイックスタート」の学習P111

質問リンク: https://automatetheboringstuff.com/chapter6/



テーブルプリンター

printTable()という名前の関数を記述しますこれは、文字列のリストのリストを取得し、各列が右寄せされた適切に編成されたテーブルに表示します。すべての内部リストに同じ数の文字列が含まれると想定します。たとえば、値は次のようになります。

printTable()

あなたのprintTable()関数は次のように出力します。



colWidths = [0] * len(tableData)

ヒント:列全体がすべての文字列に収まるように十分な幅になるように、コードは最初に各内部リストで最も長い文字列を見つける必要があります。各列の最大幅を整数のリストとして格納できます。ザ・0関数はで始めることができますtableData、同じ数のリストを作成しますcolWidths[0]の内部リストの数としての値tableData[0]。そうすれば、colWidths[1]最長の文字列の幅をに格納できますtableData[1]colWidths最長の文字列の幅をに格納できますrjust()、 等々。次に、で最大値を見つけることができます# Problem: Practice Project # The url of the problem: https://automatetheboringstuff.com/chapter6/ def printTable(Data): # Get the maximum width of each column colWidth = [0]*len(Data) for i in range(len(Data)): colWidth[i] = len(max(Data[i],key = len)) # Print for j in range(len(Data[0])): for i in range(len(Data)): print(Data[i][j].rjust(colWidth[i]), end = ' ') print(' ') # Data tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] printTable(tableData)に渡す整数幅を見つけるためのリスト

tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]
文字列メソッド。

コード:

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