如何在输出窗口中并排打印单独的多行ascii符号

2024-04-25 19:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

免责声明:我是一个相对较新的python用户和程序员。你知道吗

我正在为一组卡片构建一个类,对于__str__方法,我希望将当前在卡片组中的卡片的ascii符号返回为十三行四列。稍后,当我实际使用这个类进行游戏时,我将需要类似的逻辑来显示玩家的手。我希望找到一种方法来实现这一点,其中列的数量是可变的,行的数量取决于列的数量和列表的长度(或者简单地说,当卡片用完时停止)。这样,我的__str__返回将有4列,玩家的手将有可变的列数。你知道吗

因为我只想理解执行此操作的逻辑,所以我将问题简化为下面的代码。我做了很多研究,但是我还没有找到一个我能理解或者不使用导入库的例子。我已经学会在print语句后使用逗号来防止强制换行,但是即使使用这个工具,我也找不到一种方法来使用for和while循环来实现这一点。我还将粘贴一些来自最终用例的代码。这只是一个例子,许多没有工作,这可能是可怕的,但这是我所在的地方。你知道吗

简化用例:

# Each string in each list below would actually be one line of ascii art for
# the whole card, an example would be '|{v}   {s}   |'

deck = [['1','2','3','4'],
    ['5','6','7','8'],
    ['9','10','11','12'],
    ['a','b','c','d'],
    ['e','f','g','h'],
    ['i','j','k','l']]

# expected output in 3 columns:
#
#   1   5   9
#   2   6   10
#   3   7   11
#   4   8   12
#
#   a   e   i
#   b   f   j
#   c   g   k
#   d   h   l
#
# expected output in 4 columns:
#
#   1   5   9   a
#   2   6   10  b
#   3   7   11  c
#   4   8   12  d
#
#   e   i
#   f   j
#   g   k
#   h   l

最终用例:

def __str__(self):

    # WORKS empty list to hold ascii strings
    built_deck = []

    # WORKS fill the list with ascii strings [card1,card2,card3,card4...]
    for card in self.deck:
        built_deck.append(self.build_card(str(card[0]),str(card[1:])))

    # WORKS transform the list to [allCardsRow1,allCardsRow2,allCardsRow3,allCardsRow4...]
    built_deck = list(zip(*built_deck))

    # mark first column as position
    position = 1

    # initialize position to beginning of deck
    card = 0

    # Try to print the table of cards ***FAILURE***
    for item in built_deck:
        while position <= 4:
            print(f'{item[card]}\t',)
            card += 1
            continue
        position = 1
        print(f'{item[card]}')
        card += 1
    #return built_deck

Tags: theto方法infor数量asciiposition
1条回答
网友
1楼 · 发布于 2024-04-25 19:12:13

这里的诀窍是要认识到,你所做的是把你的卡片的矩阵进行连续的转置,然后把它们打印出来,在这里你执行操作的矩阵的大小就是你想要显示的项目的数量。我们可以在python中使用zip获得转置。你知道吗

def display(deck, number_of_columns):
    col = 0
    while col < len(deck):
        temp = deck[col:col+number_of_columns]
        temp = zip(*temp)
        for x in temp:
            for y in x:
                print(y, end=" ")
            print()
        col += number_of_columns
display(deck, 3)
print()
display(deck, 4)

输出

1 5 9 
2 6 10 
3 7 11 
4 8 12 
a e i 
b f j 
c g k 
d h l 

1 5 9 a 
2 6 10 b 
3 7 11 c 
4 8 12 d 
e i 
f j 
g k 
h l 

相关问题 更多 >