python 如何使两个不同的代码输出出现在同一个区域?

rkkpypqq  于 2023-01-29  发布在  Python
关注(0)|答案(2)|浏览(129)

我正尝试将两个输出合并在一起,以便它看起来像这样:

0 1 2
0 ? ? ?
1 ? ? ?
2 ? ? ?

但结果却变成了这样:

0 1 2
0
1
                              ? ? ?
                              ? ? ?

我尝试了这个方法来显示代码,但是我不知道如何将它们的输出放在一起

import random

rows = [3]
columns = [4]

def rowscol():
    for j in range(columns[0]):
        print(" " * 1, end="")
        print(j, end="")
    print()
    for i in range(rows[0]):
        print(i)
rowscol()

def create_game_board(rows, columns):
    board = [[random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(columns[0])] for _ in range(rows[0])]
    # If number of cells is odd, make the last cell an unused cell
    if (rows[0] * columns[0]) % 2 != 0:
        board[-1][-1] = "@"
    return board

board = create_game_board(rows,columns)

# Function to display the game board
def display_board(board):
    pad = " " * 30
    for row in board:
        line = pad + " ".join('?' if column != '@' else '@' for column in row)
        print(line)
            
display_board(board)
2ic8powd

2ic8powd1#

欢迎来到本站!
当使用多维数组时,比如你的例子中的列表列表,我希望能够很容易地索引到它们。因此,我通常把它改为dict,并使用坐标作为键。这样你甚至可以存储关于棋盘的附加信息。比如维度大小或其他任何东西。我添加了一堆注解来解释代码是如何工作的,但如果有什么不清楚的地方,请随时询问:

import random
import string

def create_game_board(rows, cols):
    board = dict()
    # save dimensions inside the dict itself
    board['cols'] = cols
    board['rows'] = rows
    for y in range(rows):
        for x in range(cols):
            # add random letter to board at (x,y)
            # x,y makes a tuple which can be a key in a dict
            # changed to use string.ascii_uppercase so that you don't forget any letter
            board[x, y] = random.choice(string.ascii_uppercase)

    # change last element to @ when both dimensions are odd
    if (rows * cols) % 2 == 1:
        board[rows-1, cols-1] = "@"
    return board

def display_board(board):
    # get dimensions
    cols, rows = board['cols'], board['rows']
    # print header
    print(' '.join([' '] + [str(x) for x in range(cols)]))
    for y in range(rows):
        # print rows
        #print(' '.join([str(y)] + [board[x, y] for x in range(cols)]))  # to display the actual letter at this location
        print(' '.join([str(y)] + ['?' if board[x, y] == '@' else '@' for x in range(cols)])) # using your display function
    print()  # separator empty line

board = create_game_board(3, 3)
display_board(board)

当我使用你的打印方法时,输出没有什么特别的,你可能需要改变它,我不确定你想如何显示它,我添加了一行,允许你打印这些坐标上的值,这是输出:

0 1 2
0 @ @ @
1 @ @ @
2 @ @ ?
cbeh67ev

cbeh67ev2#

也许是这样的?

def draw_board(board):
    print("  " + " ".join([str(i) for i in range(len(board[0]))])) # print column numbers
    for i in range(len(board)):
        row = ""
        for j in range(len(board[i])):
            row += board[i][j] + " "
        print(str(i) + " " + row)

draw_board(board)

相关问题