NinjaKlown
NinjaKlown

Reputation: 61

Nested loop, print 2 dimension nested loop

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?

Upvotes: 0

Views: 171

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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

Upvotes: 1

Related Questions