Python programming Quick Start Chapter 6 practical project reference code, python Quick Start
The Code is as follows:
A function is used to display the list in a well-organized table. Each column is right aligned.
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
'''
# The right alignment of each output column should not be the last alignment of the string,
# But not on the book. It bothered me for one night.
def printTable(tableData):
colWidths = [0] * len(tableData)
col = []
for i in range(0, len(tableData[0])):
for j in range(0, len(colWidths)):
col.append(len(tableData[j][i]))
max_len = max(col)
for i in range(0, len(tableData[0])):
for j in range(0, len(colWidths)):
print(tableData[j][i].rjust(max_len),end='')
print()
if __name__ == '__main__':
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
----------------------------------------------------------------
----------------------------------------------------------------
Apples Alice dogs
Oranges Bob cats
Cherries Carol moose
Banana David goose
This is the only way to align the right of each column. If you have any idea how to solve this problem, please leave a message.