python - 如何在 python 中打印 3x3 数组?

标签 python

我需要为名为 TicTackToe.py 的游戏打印一个 3 x 3 数组。我知道我们可以使用

以水平或垂直方式打印列表中的内容
listA=['a','b','c','d','e','f','g','h','i','j']
# VERTICAL PRINTING 
for item in listA:
        print item

输出:

a
b
c

# HORIZONTAL  PRINTING
for item in listA:
        print item,

输出:

a b c d e f g h i j

如何打印两者的混合,例如打印一个 3x3 的盒子 喜欢

a b c
d e f
g h i

最佳答案

您可以 enumerate项目,并仅每三个项目打印一个换行符:

for index, item in enumerate('abcdefghij', start=1):
    print item,
    if not index % 3:
        print

输出:

a b c
d e f
g h i
j

enumerate 默认从零开始计数,所以我设置了 start=1

正如@arekolek 评论的那样,如果您使用的是 Python 3,或者已经从 future 的 Python 2 中导入了打印函数,您可以一次性指定所有结尾的行,而不是上面的两个步骤:

for index, item in enumerate('abcdefghij', start=1):
    print(item, end=' ' if index % 3 else '\n')

关于python - 如何在 python 中打印 3x3 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903828/

相关文章:

python - 为什么在socketserver例子中只读取了1024字节

python - 遍历 boost::python vector 时出现 TypeError

python - 如何使用 Python PPTX 将上标/下标文本添加到 Powerpoint?

python - Pandas 新列具有恒定增量

python - 使用 pandas.cut() 并将其设置为数据帧的索引

Python杀死一个子进程(启动另一个进程)并再次启动它

python - 递归只生成一对。我究竟做错了什么?

python - pandas 构建逐行比较矩阵

python - 访问 scipy.sparse.csr_matrix,所有行都没有零列 j

python - For 循环仅打印 Python 中的最后一个值