Quick Start with Python Programming Chapter 6 Practice Project Reference Code

巴扎黑
Release: 2017-06-23 13:48:27
Original
1852 people have browsed it

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']]
Copy after login

'''

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)
Copy after login

----------------------------------------------------------------
----------------------------------------------------------------
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template