0
有人可以幫助我正確獲得此打印嗎?打印嵌套列表 - Python
class Deck(object):
def __init__(self):
self.cards = []
from random import shuffle
shuffle(self.cards)
#views all cards in the deck
def view_deck(self):
for x in self.cards:
print(x.name)
#takes in an (x) integer and views the top x cards of the deck
def view_number_of_cards(self, cards_to_view):
for x in self.cards[:cards_to_view]:
print(x.name)
class Player(object):
def __init__(self):
self.hand = []
self.row_1 = []
self.row_2 = []
self.row_3 = []
self.row_4 = []
self.row_5 = []
self.rows = []
self.rows.append(self.row_1)
self.rows.append(self.row_2)
self.rows.append(self.row_3)
self.rows.append(self.row_4)
self.rows.append(self.row_5)
self.graveyard = []
self.deck = Deck()
#draw a card from deck to hand
def draw_card(self):
c = self.deck.cards
cardDrawn = c.pop(0)
self.hand.append(cardDrawn)
#shuffle deck
def shuffle_deck(self):
from random import shuffle
shuffle(self.deck.cards)
def play_card(self, card, row):
self.rows[row-1].append(card)
self.graveyard.append(card)
self.hand.remove(card)
def update(self):
i = 1
for x in self.rows:
print "Lane "+str(i)+": "+str(x[0]),
i = i+1
當我試試這個:
x = Player()
x.deck.cards = [1, 2, 3, 4]
x.draw_card()
x.play_card(x.hand[0], 1)
x.rows
[[1], [], [], [], []]
x.update()
這種情況
Lane 1: 1
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
x.update()
File "C:/Users/Carl/Desktop/try.py", line 53, in update
print "Lane "+str(i)+": "+str(x[0]),
IndexError: list index out of range
在它似乎能正常工作,如果我嘗試打印控制檯 「第1道:」 +行[ 0] [0]等,但由於某種原因,我不斷收到這個IndexError,這對我來說沒有意義,因爲x列表中有絕對的其他列表。在最壞的情況下,因爲列表是預定義的(row_2 = []),所以它應該打印「第2巷道」,但這甚至不會發生。謝謝您的幫助!
感謝您的意見。出於某種原因,我認爲它只是打印空白。像「第2巷:」關於如何做到這一點的任何想法? –