python - 如何在终端中动态打印字符串表?

标签 python dynamic terminal formatting tabular

我需要动态创建一个字典字典,然后将它们打印在终端的整齐表格中。最终,我将添加到每个字典并重新打印表格。

这是我到目前为止的代码:

def handy(self, play_deck):
    a = raw_input('How many hands? ')
    for i in range(int(a)):
        h = "hand" + str(i+ 1) # dynamilly create key
        q, play_deck = self.deal(self.full_deck) # pull cards from deck
        self.dict_of_hands.setdefault(h, q) # load up dict of hands

    hand_keys = self.dict_of_hands.keys()
    the_hands = self.dict_of_hands
    print "\n"
    for hand in hand_keys:
        for card in range(len(the_hands[hand].keys())):
            print hand
            print the_hands[hand][card]

我的输出是这样的:

How many hands? 4

hand4
6 of Clubs
hand4
4 of Diamonds
hand1
8 of Diamonds
hand1
10 of Hearts
hand2
10 of Hearts
hand2
5 of Clubs
hand3
9 of Diamonds
hand3
3 of Hearts

我想要:

hand1           hand2           hand3            hand4
2 of hearts     8 of spades     ace of clubs     jack of diomonds
5 of diamonds   ...             ...              ...etc.

我在 SO 上看到的示例是基于已知数量的列。这需要是动态的。

最佳答案

要转换为行列表,请使用 zip:

header = dict_of_hands.keys()
rows = zip(*dict_of_hands.items())

import texttable
table = texttable.Texttable()
table.header(header)
table.add_rows(rows, header=False)
print table.draw()

关于python - 如何在终端中动态打印字符串表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078802/

相关文章:

linux - 运行 nohup 命令后如何查看输出控制台?

python - 异步运行一些 Python 代码的正确方法是什么?

linq - Linq to Entities中的动态where子句

c# - 在 C# 中动态创建和公开 SOAP 服务及其 WSDL(使用自定义 TCP 监听器!)

terminal - 在 Alacritty 中逐字移动光标

linux - 重定向正在运行的进程的终端输出

python - 如何在没有警告的情况下在 Pandas 中进行分配?

python - 无法为 cartopy linux 安装 Proj 8.0.0

python - 从DoesNotExist异常实例获取查找参数

c# - 为什么 C# 动态类型是静态的?