Table Printer Excercise











up vote
2
down vote

favorite
1












im new two Python and i came to the following excercise:




Write a function named printTable() that takes a list of lists of
strings and displays it in a well-organized table with each column
right-justified. Assume that all the inner lists will contain the same
number of strings. For example, the value could look like this:



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]


Your printTable() function would print the following:



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



my solution is this:



table_printer.py



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
"""
Print table neatly formatted:
e.g:

[['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

becomes:

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
"""
# make list of ints to store later max len element of each list
colWidths = [0] * len(tableData)

# Store maxlen of each list
i = 0
while i < len(tableData):
colWidths[i] = len(max(tableData[i], key=len))
i = i + 1

# Print formatted
for x in range(len(tableData[0])):
for y in range(len(colWidths)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='n')

printTable(tableData)


I wonder if this is a good solution or there is a easier/better way. It took me quite some time to come up with a solution. Still i feel its probaly not very elegant.
Maybe im thinking to difficult because i come from c/c++ were you often have to do more stuff by hand.



I read is often not a good idea in python to write loops like in other languages with explicit indices (what i basically did here). Are there any alternatives here?










share|improve this question






















  • You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
    – Sigur
    3 hours ago















up vote
2
down vote

favorite
1












im new two Python and i came to the following excercise:




Write a function named printTable() that takes a list of lists of
strings and displays it in a well-organized table with each column
right-justified. Assume that all the inner lists will contain the same
number of strings. For example, the value could look like this:



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]


Your printTable() function would print the following:



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



my solution is this:



table_printer.py



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
"""
Print table neatly formatted:
e.g:

[['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

becomes:

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
"""
# make list of ints to store later max len element of each list
colWidths = [0] * len(tableData)

# Store maxlen of each list
i = 0
while i < len(tableData):
colWidths[i] = len(max(tableData[i], key=len))
i = i + 1

# Print formatted
for x in range(len(tableData[0])):
for y in range(len(colWidths)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='n')

printTable(tableData)


I wonder if this is a good solution or there is a easier/better way. It took me quite some time to come up with a solution. Still i feel its probaly not very elegant.
Maybe im thinking to difficult because i come from c/c++ were you often have to do more stuff by hand.



I read is often not a good idea in python to write loops like in other languages with explicit indices (what i basically did here). Are there any alternatives here?










share|improve this question






















  • You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
    – Sigur
    3 hours ago













up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





im new two Python and i came to the following excercise:




Write a function named printTable() that takes a list of lists of
strings and displays it in a well-organized table with each column
right-justified. Assume that all the inner lists will contain the same
number of strings. For example, the value could look like this:



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]


Your printTable() function would print the following:



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



my solution is this:



table_printer.py



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
"""
Print table neatly formatted:
e.g:

[['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

becomes:

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
"""
# make list of ints to store later max len element of each list
colWidths = [0] * len(tableData)

# Store maxlen of each list
i = 0
while i < len(tableData):
colWidths[i] = len(max(tableData[i], key=len))
i = i + 1

# Print formatted
for x in range(len(tableData[0])):
for y in range(len(colWidths)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='n')

printTable(tableData)


I wonder if this is a good solution or there is a easier/better way. It took me quite some time to come up with a solution. Still i feel its probaly not very elegant.
Maybe im thinking to difficult because i come from c/c++ were you often have to do more stuff by hand.



I read is often not a good idea in python to write loops like in other languages with explicit indices (what i basically did here). Are there any alternatives here?










share|improve this question













im new two Python and i came to the following excercise:




Write a function named printTable() that takes a list of lists of
strings and displays it in a well-organized table with each column
right-justified. Assume that all the inner lists will contain the same
number of strings. For example, the value could look like this:



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]


Your printTable() function would print the following:



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



my solution is this:



table_printer.py



tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

def printTable(tableData):
"""
Print table neatly formatted:
e.g:

[['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

becomes:

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
"""
# make list of ints to store later max len element of each list
colWidths = [0] * len(tableData)

# Store maxlen of each list
i = 0
while i < len(tableData):
colWidths[i] = len(max(tableData[i], key=len))
i = i + 1

# Print formatted
for x in range(len(tableData[0])):
for y in range(len(colWidths)):
print(tableData[y][x].rjust(colWidths[y]), end=' ')
print(end='n')

printTable(tableData)


I wonder if this is a good solution or there is a easier/better way. It took me quite some time to come up with a solution. Still i feel its probaly not very elegant.
Maybe im thinking to difficult because i come from c/c++ were you often have to do more stuff by hand.



I read is often not a good idea in python to write loops like in other languages with explicit indices (what i basically did here). Are there any alternatives here?







python strings formatting






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 9 hours ago









Sandro4912

681121




681121












  • You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
    – Sigur
    3 hours ago


















  • You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
    – Sigur
    3 hours ago
















You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
– Sigur
3 hours ago




You can compute the maximal length on each row by np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData]) which returns [8 5 5]. These numbers will be used to format the strings.
– Sigur
3 hours ago










1 Answer
1






active

oldest

votes

















up vote
0
down vote













Here is my proposal.



import numpy as np

tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]

max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

for col in range(len(tableData[0])):
for i in range(len(tableData)):
print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
print ""


Output



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





share|improve this answer





















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208246%2ftable-printer-excercise%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Here is my proposal.



    import numpy as np

    tableData = [['apples', 'oranges', 'cherries', 'banana'],
    ['Alice', 'Bob', 'Carol', 'David'],
    ['dogs', 'cats', 'moose', 'goose']]

    max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

    for col in range(len(tableData[0])):
    for i in range(len(tableData)):
    print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
    print ""


    Output



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





    share|improve this answer

























      up vote
      0
      down vote













      Here is my proposal.



      import numpy as np

      tableData = [['apples', 'oranges', 'cherries', 'banana'],
      ['Alice', 'Bob', 'Carol', 'David'],
      ['dogs', 'cats', 'moose', 'goose']]

      max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

      for col in range(len(tableData[0])):
      for i in range(len(tableData)):
      print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
      print ""


      Output



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





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Here is my proposal.



        import numpy as np

        tableData = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

        max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

        for col in range(len(tableData[0])):
        for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
        print ""


        Output



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





        share|improve this answer












        Here is my proposal.



        import numpy as np

        tableData = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

        max_len = np.array([np.array(max([len(xii) for xii in xi])) for xi in tableData])

        for col in range(len(tableData[0])):
        for i in range(len(tableData)):
        print ("{:>%d}" % max_len[i]).format(tableData[i][col]),
        print ""


        Output



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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 3 hours ago









        Sigur

        1689




        1689






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208246%2ftable-printer-excercise%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Costa Masnaga