Home  >  Article  >  Backend Development  >  Quick Start with Python Programming Chapter 6 Practice Project Reference Code

Quick Start with Python Programming Chapter 6 Practice Project Reference Code

巴扎黑
巴扎黑Original
2017-06-23 13:48:271859browse

The code is as follows:

The meaning of the question is to display a list of lists in a well-organized table through a function, with each column 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

'''

#Output each column right-aligned I think it should not be a string Is the last one aligned?

#But it’s not the one in the book. It bothered me all 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

The right alignment of each column can only be like this. I can’t think of a better solution. If anyone knows how to solve it, please leave a message

The above is the detailed content of Quick Start with Python Programming Chapter 6 Practice Project Reference Code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn