简体   繁体   中英

How to print lists within a list in separate columns using for loops?

The problem is from Chapter 6 of ATBS. It is to create a function that is passed a list of lists and then print each list but justified so that each column is neat and flush regardless of the length of the strings within the list.

I created an empty list with the same number of elements as each embedded list (assuming all same length) and found the maximum string length within each list and this number to the empty list. Then called on to print each list justified by the maximum string length.

table = [['Tom','Dick','Harry','John'],
         ['Apples','Oranges','Strawberries','Grapes'],
         ['Brocolli', 'Asparagus', 'Carrots', 'Potatoes']]




def printTable(tableData):
    colWidths = [0] * len(tableData)
    for i in range(len(tableData)):
        colWidths[i] = max(len(j) for j in tableData[i])
    for i in range(len(tableData)):
        for j in tableData[i]:
            print(j.rjust(colWidths[i]))



printTable(table)

This prints the following

  Tom
 Dick
Harry
 John
      Apples
     Oranges
Strawberries
      Grapes
 Brocolli
Asparagus
  Carrots
 Potatoes

but i want it in three separate columns as opposed to just one. I know this can simply be done with zip but I haven't covered that yet. I want to understand how to do it using for loops before covering new content just to get the job done as I don't feel that will help me learn the fundamentals properly.

try this:

table = [['Tom','Dick','Harry','John'],
         ['Apples','Oranges','Strawberries','Grapes'],
         ['Brocolli', 'Asparagus', 'Carrots', 'Potatoes']]




def printTable(tableData):
    colWidths = [0] * len(tableData)
    for i in range(len(tableData)):
        colWidths[i] = max(len(j) for j in tableData[i])
    for i in range(len(tableData)):
        for j in tableData[i]:
            print(j.rjust(sum(colWidths[:i+1])))



printTable(table)

all I did was change rjust to justify not just for the current column, but for all previous columns as well.

good thing you already put all widths in a list :)

Here's something to get started: the first row (let's call it row0 because it's the one with index 0) is

row0 = [x[0] for x in table]  

For each list x in the table you take the first element.

Construct the second row similarly.

To get all rows put this in a loop for i in range(4)

Note that if one of the elements in table has a different length you have to take care of that somehow, but in your example all elements in table have the same length 4 .

    table = [['Tom','Dick','Harry','John'],
         ['Apples','Oranges','Strawberries','Grapes'],
         ['Brocolli', 'Asparagus', 'Carrots', 'Potatoes']]




def printTable(tableData):
    buffer = []
    colWidths = [0] * len(tableData)
    for i in range(len(tableData)):
        colWidths[i] = max(len(j) for j in tableData[i])
    for j in range(len(tableData[i])):
        buffer.append("") #filling the buffer array with empty string could have used buffer = ["" for i in range(len(tableData[i]]))]
    for i in range(len(tableData)): 
        for j in range(len(tableData[i])):
            buffer[j] += (tableData[i][j].rjust(colWidths[i]))
            buffer[j] += " "
    for i in range(len(buffer)):
        print(buffer[i])






printTable(table)

All I did was to define a buffer array to store each row, after doing that I've created another for loop to print them. When you print a line you can't go back to that line and add a new element so you have to create the line you want to print first, then print it. Since the output that you wanted has an item from each list, I've concatenated them into a string and separated them with a space character.

The output is

  Tom       Apples  Brocolli
 Dick      Oranges Asparagus
Harry Strawberries   Carrots
 John       Grapes  Potatoes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM