简体   繁体   中英

Create a table from a list of tuples in Python 3

I have homework where I have to take a list containing tuples and print out a table. For example, the list might look like this:

data = [('Item1', a1, b1, c1, d1, e1, f1),
        ('Item2', a2, b2, c2, d2, e2, f2),
        ('Item3', a3, b3, c3, d3, e3, f3)]

I would have to print out this:

            Item1   Item2   Item3
DataA:      a1      a2      a3
DataB:      b1      b2      b3
DataC:      c1      c2      c3
DataD:      d1      d2      d3
DataE:      e1      e2      e3
DataF:      f1      f2      f3

I have initialised a list:

data_headings = ['','DataA:','DataB','DataC:','DataD:','DataE':,'DataF:']

My teacher has also given us the option to use a function he created:

display_with_padding(str):
     print("{0: <15}".format(s), end = '')

Some guidance with how to do this will be much appreciated. I've been playing with this for the past day and I still am unable to work it out.

def display_with_padding(s):
     print("{0: <15}".format(s), end='')

def print_row(iterable):
    [display_with_padding(x) for x in iterable]
    print()

def main():

    data = [
        ('Item1', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1'),
        ('Item2', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'),
        ('Item3', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3')
    ]

    col_headers = [''] + [x[0] for x in data]  # Build headers
    print_row(col_headers)


    labels = ['DataA:','DataB:','DataC:','DataD:','DataE:','DataF:']

    # Build each row
    rows = []
    for row_num, label in enumerate(labels, start=1):
        content = [label]
        for col in data:
            content.append(col[row_num])
        rows.append(content)

    for row in rows:
        print_row(row)


if __name__ == '__main__':
    main()

The trick is to iterate over each element of the table in some order. Rows first or columns first?

Because you're printing line by line, you must iterate over the rows first, and look up the corresponding value in each column. Observe that data is a list of columns, while the second list provides a label for each row. I've renamed it to row_labels in the following demonstration.

def display_with_padding(s):
  print("{0: <15}".format(s), end = '')

data = [('Item1', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1'),
        ('Item2', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'),
        ('Item3', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3')]

row_labels = ['', 'DataA:', 'DataB:', 'DataC:', 'DataD:', 'DataE:', 'DataF:']

for row_index, label in enumerate(row_labels):
  display_with_padding(label)
  for column in data:
    display_with_padding(column[row_index])
  print()

Note the use of enumerate() to get the index and value at the same time as we iterate over row_labels .

Oh, and I fixed a few bugs in the code you posted. There were a couple of problems with the function definition (missing def and bad parameter name) plus a syntax error in the row labels. I renamed the row labels, too.

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