我需要为名为 TicTackToe.py 的游戏打印一个 3 x 3 数组。我知道我们可以使用以下方法以水平或垂直方式打印列表中的内容
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
我怎样才能打印两者的混合,例如打印 3x3 盒子
喜欢
a b c
d e f
g h i
You can enumerate https://docs.python.org/2/library/functions.html#enumerate项目,并仅每三个项目打印一个换行符:
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
默认从零开始计数,所以我设置start=1
.
正如 @arekolek 评论的那样,如果您使用的是 Python 3,或者已经从 Python 2 的 future 导入了 print 函数,您可以一次性指定所有结尾的行,而不是上面的两个步骤:
for index, item in enumerate('abcdefghij', start=1):
print(item, end=' ' if index % 3 else '\n')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)