如何将数据从列表列表转换为可读表(或列组)?

时间:2013-05-28 00:44:12

标签: python list python-2.7

我有以下代码,它基本上返回了5个列表的列表(player1Hand)(在这种情况下,是关于所述手牌的个人信息)。

def getPlayer2Hand(handAmount):
    getPlayer2Deck()
    player2Hand = []

    for i in range(handAmount):
        card = []
        card.append(deckListPlayer2Full[i]['NameOfCard'])
        card.append(deckListPlayer2Full[i]['Attack'])
        card.append(deckListPlayer2Full[i]['Defense'])
        card.append(deckListPlayer2Full[i]['Magic'])
        card.append(deckListPlayer2Full[i]['Shield'])
        player2Hand.append(card)

    return player2Hand

如何将列表“player2Hand"中的信息打印到可读列或表格中?我想使用上面的dict键(NameOfCardAttack等。 )作为标题。

我尝试使用TextTable,但似乎无法让它工作。

以下是player2Hand的示例:

[['Knight', '500', '500', '0', '0'], 
['Mage', '0', '0', '500', '500'], 
['Mage', '0', '0', '500', '500'], 
['Mage', '0', '0', '500', '500'], 
['Mage', '0', '0', '500', '500']]

2 个答案:

答案 0 :(得分:1)

位字符串格式化可能会有所帮助:

>>> data = [['Knight', '500', '500', '0', '0'],
            ['Mage', '0', '0', '500', '500'],
            ['Mage', '0', '0', '500', '500'],
            ['Mage', '0', '0', '500', '500'],
            ['Mage', '0', '0', '500', '500']]

>>> frmt = '{:10s}' + 4 * '{:>12s}'
>>> for line in data::
        print(frmt.format(*line))

结果:

Knight             500         500           0           0
Mage                 0           0         500         500
Mage                 0           0         500         500
Mage                 0           0         500         500
Mage                 0           0         500         500

答案 1 :(得分:0)

快速而又脏兮兮地捅你可能想做的事情:

>>> x = [['Knight', '500', '500', '0', '0'],['Mage', '0', '0', '500', '500'], ['Mage', '0', '0', '500', '500'], ['Mage', '0', '0', '500', '500'],  ['Mage', '0', '0', '500', '500']]
>>> for row in x:
...     output = [row[0].ljust(20)]
...     for col in row[1:]:
...         output.append(col.rjust(10))
...     print ''.join(output)
... 
Knight                     500       500         0         0
Mage                         0         0       500       500
Mage                         0         0       500       500
Mage                         0         0       500       500
Mage                         0         0       500       500