打印嵌套列表-Python
有人能帮我把这张照片印好吗打印嵌套列表-Python,python,list,printing,for-loop,nested-lists,Python,List,Printing,For Loop,Nested Lists,有人能帮我把这张照片印好吗 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
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:1
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
x、 更新()
更新中第53行的文件“C:/Users/Carl/Desktop/try.py”
打印“Lane”+str(i)+“:”+str(x[0]),
索引器:列表索引超出范围
在控制台中,如果我尝试打印“lane1:+行[0][0]等,它似乎工作正常,但出于某种原因,我一直得到这个索引器,这对我来说没有意义,因为在x-list范围内肯定还有其他列表。在最坏的情况下,因为列表是预定义的(row_2=[]),所以它应该打印“Lane 2:”,但这根本不会发生。谢谢你的帮助 问题在于,正如您所说,
行2=[]
。因为它是空的,所以在索引0处没有元素
要得到空白的“Lane x:”行,您可以这样重写更新:
def update(self):
for x in self.rows:
for i in range(5):
print("Lane {}: ".format(i), end='')
if len(x):
print(x[0])
else:
print()
您还需要在文件的开头添加导入,以获得打印函数,而不是打印语句:
from __future__ import print_function
谢谢,这很有道理。出于某种原因,我认为它只会打印空白。比如“第二条车道:”你知道怎么做吗?