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

问题描述 投票:3回答:1

免责声明:我是一个相对较新的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
python logic
1个回答
1
投票

这里的诀窍就是要意识到你正在做的是对卡的矩阵进行连续的转置并将它们打印到你预先形成操作的矩阵大小的位置是你想要显示的项目数。我们可以在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 
© www.soinside.com 2019 - 2024. All rights reserved.