python-3.x - 如何将循环中的字符串附加到单个输出行?

标签 python-3.x numpy loops

因此,我正在尝试制作一个基于文本的 connect-4 游戏,以便更好地理解 Python 及其实际工作原理。

简短版本

  • 如何将 while 循环的每次运行中的打印文本附加到 while 循环之前存在的打印输出
  • 在下面看到的两种方法(正在进行的工作和当前成功工作的方法)中,哪一种是执行所需输出的更好做法?

长版

我正在尝试使用循环系统在每次转动后以均匀间隔且美观的格式打印出数组,以便用户在进行下一次转动之前对当前板的外观有清晰的反馈。 为此,我希望能够拥有尽可能小的代码行,以便更容易阅读代码本身。尽管这可能不是执行此场景的最佳实践,但我想更好地理解这种编码方式,以便在需要时将其应用到 future 的项目中。

就实际执行而言,我尝试使用 while 循环将数组的 7 个位置依次追加到同一输出行中,以获取同一行中的数组位置。之后,我想打印上一行下方的下一行,如“所需输出”下面的代码所示。

预先感谢您的回答、建议和评论。

工作进行中

import numpy as np
ARRAY = np.zeros(shape=(6, 7), dtype = 'int8')
# In reality I will be using an empty array that gradually gets populated
# Zeros are used for ease of asking the question

def Display_board():
    i = 0
    while i < 7:
        j = 0
        print("  ", end = " ")
        while j < 8:
            print(str(ARRAY[i][j]))
            j += 1
        i += 1

正在进行的工作输出

 0
   0
0
0
0
0
0
0
   0
0
0
0
0
0
0
# It goes on but didn't include as it would take up unnessary space in the question

如果我将打印数组的行更改为如下所示,我会得到另一个不需要的输出

print(str(ARRAY[i][j]), end = " ")

#output
  0 0 0 0 0 0 0    0 0 0 0 0 0 0    0 0 0 0 0 0 0    0 0 0 0 0 0 0    0 0 0 0 0 0 0    0 0 0 0 0 0 0

当前工作方法 - 提供所需的输出

def Display_board():
   for i in range(6):
       print("   " + str(ARRAY[i][0]) + "  " + str(ARRAY[i][1]) + "  " + str(ARRAY[i][2]) \
       + "  " + str(ARRAY[i][3]) + "  " + str(ARRAY[i][4]) + "  " + str(ARRAY[i][5])\
       + "  " + str(ARRAY[i][6]))

期望的输出

  0  0  0  0  0  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  0  0

最佳答案

简单的修复方法是在 j 的 while 循环内的打印上使用 end=' ',然后添加 print()之后:

def Display_board():
    i = 0
    while i < 6:
        j = 0
        print("  ", end = " ")
        while j < 7:
            print(str(ARRAY[i][j]), end=" ")
            j += 1
        print()
        i += 1

输出:

   0 0 0 0 0 0 0 
   0 0 0 0 0 0 0 
   0 0 0 0 0 0 0 
   0 0 0 0 0 0 0 
   0 0 0 0 0 0 0 
   0 0 0 0 0 0 0 

您还可以使用带有 join 的嵌套列表理解来实现一行输出:

def Display_board():
    print('\n'.join(' '.join(['  '] + [str(ARRAY[i][j]) for j in range(7)]) for i in range(6)))

关于python-3.x - 如何将循环中的字符串附加到单个输出行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244771/

相关文章:

R: 如何制作 MCMCglmm 循环

python - 连接/合并每个 Json 文件,python

javascript - 在 foreach 循环内调用 javascript 函数,等待回复?

python - 类型错误 : object of type 'NoneType' has no len() while iterating through a list

python - 使用 FFT 分析 Google 趋势时间序列的季节性

python - 使用 Python 进行反距离加权 (IDW) 插值

python - reshape 3D 数组中的一组数组

python - 为什么列表结果与预期不同?

python - 根据条件递归地将键添加到嵌套字典中

linux - Imagemagick 的导入速度慢得令人沮丧