首页 > 解决方案 > 如何在输出窗口中并排打印单独的多行 ascii 符号

问题描述

免责声明:总的来说,我是一个相对较新的 python 用户和程序员。

我正在为一副纸牌构建一个类,对于__str__我想要将当前在纸牌中的卡片的 ascii 符号返回为 13 行,每列 4 列的方法。稍后,当我实际将这个类用于游戏时,我将需要类似的逻辑来显示玩家的手牌。我希望找到一种方法来做到这一点,其中列数是可变的,并且行数取决于列数和列表的长度(或者说清楚,当卡用完时停止)。这样,它将适用于我__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

标签: pythonlogic

解决方案


诀窍是要意识到你正在做的事情是对卡片矩阵进行连续转置并打印它们,其中你执行操作的矩阵大小是你想要显示的项目数。我们可以zip在 python 中使用转置。

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 

推荐阅读