python - 如何在输出窗口中并排打印单独的多行 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
解决方案
诀窍是要意识到你正在做的事情是对卡片矩阵进行连续转置并打印它们,其中你执行操作的矩阵大小是你想要显示的项目数。我们可以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
推荐阅读
- tinymce - 在 tinymce 页脚中将计数从增加变为减少
- python - 使用条件连接循环中的字符串列表中的元素
- sql-server - 创建在一个字段中处理多个字段的视图
- laravel - 通过 composer 安装 laravel 和 backoffice(全新安装和集成)
- html - 在 Firefox 的 Bootstrap 布局中使用溢出和粘性项目有时会产生不需要的垂直空间
- php - 查询数据库的最后修改日期
- python - 使用opencv-python从不同cpu上的同一视频中获取不同的有效帧号?
- azure - 使用 Invoke-AzsRegistrationValidation 时 Azure Powershell 命令失败
- algorithm - 将 14 人分成 4 人一组,这样每个人至少见面一次
- c# - ImageHandlers 和 GetEncoder 在当前上下文 xamarin 中不存在,该怎么办?