【发布时间】:2018-09-16 21:23:04
【问题描述】:
免责声明:我是一个相对较新的 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
【问题讨论】: