1

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

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

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 上看到的示例基于已知数量的列。这需要是动态的。

4

3 回答 3

1

要转换为行列表,请使用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()
于 2012-08-22T20:28:57.583 回答
1

好的。采用@ecatmur 提供的内容,我现在有以下内容,这似乎目前可以使用。

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

    first_cards = []
    second_cards = []
    for hand in the_hands:
        # print the_hands[hand][0]
        first_cards.append(the_hands[hand][0])

    for hand in the_hands:
        # print the_hands[hand][1]
        second_cards.append(the_hands[hand][1])         

    header = self.dict_of_hands.keys()


    table = texttable.Texttable()
    table.header(header)
    table.add_rows([first_cards, second_cards], header=False)
    print table.draw()

输出是:

How many hands? 4
+---------------+---------------+------------------+---------------+
|     hand4     |     hand1     |      hand2       |     hand3     |
+===============+===============+==================+===============+
| Jack of Clubs | 9 of Diamonds | Jack of Diamonds | 4 of Spades   |
+---------------+---------------+------------------+---------------+
| 6 of Diamonds | 10 of Spades  | 9 of Diamonds    | Ace of Hearts |
+---------------+---------------+------------------+---------------+

拼图的最后一块将使以下行动态化:

table.add_rows([first_cards, second_cards], header=False)

最终,我需要每只手的长度都不同。

于 2012-08-22T21:09:14.830 回答
0

看看这个秘籍:为文本界面渲染表格

于 2012-08-22T20:18:02.607 回答