Reputation: 868
I need to print a 3 x 3 array for a game called TicTackToe.py. I know we can print stuff from a list in a horizontal or vertical way by using
listA=['a','b','c','d','e','f','g','h','i','j']
# VERTICAL PRINTING
for item in listA:
print item
Output:
a
b
c
or
# HORIZONTAL PRINTING
for item in listA:
print item,
Output:
a b c d e f g h i j
How can I print a mix of both, e.g. printing a 3x3 box like
a b c
d e f
g h i
Upvotes: 16
Views: 13552
Reputation: 11
An easy solution #The end="" will print the values in the same line and the empty print() will make the control move to the immediately next line. #Don't use "\n", for it will create an empty line between the rows!
s = []
for i in range(3):
s.append(list(map(int, input().split())))
for i in range(3):
for j in range(3):
print(s[i][j],"",end="")
print()
Upvotes: 0
Reputation: 294
print ''.join(' '*(n%3!=0)+l+'\n'*(n%3==2) for n,l in enumerate(listA))
a b c
d e f
g h i
j
Python is awesome.
Upvotes: 0
Reputation: 24133
You can enumerate
the items, and print a newline only every third item:
for index, item in enumerate('abcdefghij', start=1):
print item,
if not index % 3:
print
Output:
a b c
d e f
g h i
j
enumerate
starts counting from zero by default, so I set start=1
.
As @arekolek comments, if you're using Python 3, or have imported the print function from the future for Python 2, you can specify the line ending all in one go, instead of the two steps above:
for index, item in enumerate('abcdefghij', start=1):
print(item, end=' ' if index % 3 else '\n')
Upvotes: 23
Reputation: 30813
One method which have not been mentioned: Get the slice of the list mathematically and print
by the slice of the list.
In Python 2.x
:
listA=['a','b','c','d','e','f','g','h','i','j']
val = (len(listA) + 2) // 3
for i in range(val):
print(' '.join(listA[i*3:(i+1)*3]))
In Python 3.x
:
listA=['a','b','c','d','e','f','g','h','i','j']
val = (len(listA) + 2) // 3
for i in range(val):
print(*listA[i*3:(i+1)*3], sep=" ")
Upvotes: 1
Reputation: 114320
You could use the format method of the string object:
for i in range(3):
print "{} {} {}".format(*listA[3*i:3*i+3])
Also, instead of multiplying the index by 3 at every iteration, you can just take steps of three elements through the list:
for i in range(0, len(listA), 3):
print "{} {} {}".format(*listA[i:i+3])
Upvotes: 4
Reputation: 180411
You can use the logic from the grouper recipe:
listA=['a','b','c','d','e','f','g','h','i','j']
print("\n".join(map(" ".join, zip(*[iter(listA)] * 3))))
a b c
d e f
g h i
If you don't want to lose elements use izip_longest
with an empty string as a fillvalue:
listA=['a','b','c','d','e','f','g','h','i','j']
from itertools import izip_longest
print("\n".join(map(" ".join, izip_longest(*[iter(listA)] * 3,fillvalue=""))))
Which differs in that it keeps the j:
a b c
d e f
g h i
j
You can put the logic in a function and call it when you want to print, passing in whatever values you want.
from itertools import izip_longest
def print_matrix(m,n, fill):
print( "\n".join(map(" ".join, izip_longest(*[iter(m)] * n, fillvalue=fill))))
Or without itertools just chunk and join, you can also take a sep
arg to use as the delimiter:
def print_matrix(m,n, sep):
print( "\n".join(map("{}".format(sep).join, (m[i:i+n] for i in range(0, len(m), n)))))
You just need to pass the list and the size for each row:
In [13]: print_matrix(listA, 3, " ")
a b c
d e f
g h i
j
In [14]: print_matrix(listA, 3, ",")
a,b,c
d,e,f
g,h,i
j
In [15]: print_matrix(listA, 4, ",")
a,b,c,d
e,f,g,h
i,j
In [16]: print_matrix(listA, 4, ";")
a;b;c;d
e;f;g;h
i;j
Upvotes: 11
Reputation: 5381
An alternative to the two answers given here is to use something that does the formatting for you, like numpy. This is an external dependency you might not want in general, but if you're already storing things in grids/matrices, it can be a logical choice:
from numpy import array
str(array(listA).reshape((3,3)))
Put it in an array, reshape it in your favourite (compatible) shape, and make it a string. Couldn't be more intuitive!
Upvotes: 5
Reputation: 2038
A simple approach would be to use the modulo operator:
listA=['a','b','c','d','e','f','g','h','i','j']
count = 0
for item in listA:
if not count % 3:
print
print item,
count += 1
As pointed out by Peter Wood, you can use the enumerator operator, to avoid the count variable:
listA=['a','b','c','d','e','f','g','h','i','j']
listB = enumerate(listA)
for item in listB:
if not item[0] % 3:
print
print item[1],
Upvotes: 8