Reputation: 39
I have a list of lists that represent a card game. The list represent the rows and columns of the cards. I'm trying to print the cards in neat columns and rows but I cannot seem to figure it out. Here is what I have:
maxCol = len(tableaus[0])
for row in tableaus:
rowLength = len(row)
if rowLength > maxCol:
maxCol = rowLength
tab = []
for colIndex in range(maxCol):
tab.append([])
for row in tableaus:
if colIndex < len(row):
tab[colIndex].append(row[colIndex])
for s in tab:
print("{:4s}".format(str(s)))
the output currently is:
=================Tableaus=================
---1----2----3----4----5----6----7----8---
[K♠, Q♠, J♠, 10♠, 9♠, 8♠, 7♠, 6♠]
[5♠, 4♠, 3♠, 2♠, A♠, K♥, Q♥, J♥]
[10♥, 9♥, 8♥, 7♥, 6♥, 5♥, 4♥, 3♥]
[2♥, A♥, K♦, Q♦, J♦, 10♦, 9♦, 8♦]
[7♦, 6♦, 5♦, 4♦, 3♦, 2♦, A♦, K♣]
[Q♣, J♣, 10♣, 9♣, 8♣, 7♣, 6♣, 5♣]
[4♣, 3♣, 2♣, A♣]
but should be:
=================Tableaus=================
---1----2----3----4----5----6----7----8---
K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠
5♠ 4♠ 3♠ 2♠ A♠ K♥ Q♥ J♥
10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥
2♥ A♥ K♦ Q♦ J♦ 10♦ 9♦ 8♦
7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♦ K♣
Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣
4♣ 3♣ 2♣ A♣
tableaus = [[K♠, 5♠, 10♥, 2♥, 7♦, Q♣, 4♣], [Q♠, 4♠, 9♥, A♥, 6♦, J♣, 3♣], [J♠, 3♠, 8♥, K♦, 5♦, 10♣, 2♣], [10♠, 2♠, 7♥, Q♦, 4♦, 9♣, A♣], [9♠, A♠, 6♥, J♦, 3♦, 8♣], [8♠, K♥, 5♥, 10♦, 2♦, 7♣], [7♠, Q♥, 4♥, 9♦, A♦, 6♣], [6♠, J♥, 3♥, 8♦, K♣, 5♣]]
Any tips?
Upvotes: 0
Views: 552
Reputation: 177971
Here's a "Minimal, Complete, Verifiable Answer", assuming tableaus is defined as shown. If this doesn't work for you, you now know why I asked for an MCVE.
#coding:utf8
tableaus = [['K♠', 'Q♠', 'J♠', '10♠', '9♠', '8♠', '7♠', '6♠'],
['5♠', '4♠', '3♠', '2♠', 'A♠', 'K♥', 'Q♥', 'J♥'],
['10♥', '9♥', '8♥', '7♥', '6♥', '5♥', '4♥', '3♥'],
['2♥', 'A♥', 'K♦', 'Q♦', 'J♦', '10♦', '9♦', '8♦'],
['7♦', '6♦', '5♦', '4♦', '3♦', '2♦', 'A♦', 'K♣'],
['Q♣', 'J♣', '10♣', '9♣', '8♣', '7♣', '6♣', '5♣'],
['4♣', '3♣', '2♣', 'A♣']]
print('=================Tableaus=================')
print('---1----2----3----4----5----6----7----8---')
for row in tableaus:
print(''.join(format(c,'>5') for c in row))
This uses a list comprehension to format each element in the row in a width 5, right-justified field, then joins each element together into a single string.
=================Tableaus================= ---1----2----3----4----5----6----7----8--- K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠ 5♠ 4♠ 3♠ 2♠ A♠ K♥ Q♥ J♥ 10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥ 2♥ A♥ K♦ Q♦ J♦ 10♦ 9♦ 8♦ 7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♦ K♣ Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣ 4♣ 3♣ 2♣ A♣
Upvotes: 0
Reputation: 104792
Currently you're formatting each row with a single call to str.format
. That doesn't do what you want because the row is a list, which prints out with brackets and uneven spacing. You want to be applying your formatting to each element of the list instead. Try:
for row in tab:
print("".join(format(str(item), ">4") for item in row)
Upvotes: 2