0

I am having trouble with nested loops and lists. I need to print a 2 dimension multiplication table.

mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]

print mult_table[0][0],mult_table[0][1],mult_table[0][2]
print mult_table[1][0],mult_table[1][1],mult_table[1][2]
print mult_table[2][0],mult_table[2][1],mult_table[2][2]

1 2 3 
2 4 6
3 6 9

this is what i get, but the book wants this output

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9

im not 100% sure how to do this, I know i need to use a loop, but how do i put the vertical dashes in?

1 Answer 1

1

Use join to join a sequence of strings with some text between them:

mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]

for row in mult_table:
    print ' | '.join(str(x) for x in row)

Output:

1 | 2 | 3
2 | 4 | 6
3 | 6 | 9

This will lose its prettiness if one of the elements is wider than one character, however. If you know the maximum width, you can tweak it to look like this:

mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 666, 9],
]

for row in mult_table:
   print ' | '.join('{0:<4}'.format(x) for x in row)

Output:

1    | 2    | 3
2    | 4    | 6
3    | 666  | 9

To be really flexible, we can calculate the maximum width of any element in the array, and use that as our width. str.rjust() will right-justify a string to a certain width.

mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 66666, 9],
]

maxval = max(max(mult_table))
maxwid = len(str(maxval))

for row in mult_table:
   print ' | '.join(str(x).rjust(maxwid) for x in row)

Output:

    1 |     2 |     3
    2 |     4 |     6
    3 | 66666 |     9
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.