[英]Printing nested lists - 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
在控制台中,如果我尝试打印“Lane 1:”+ rows [0] [0]等,它似乎工作正常但由于某种原因我不断得到这个对我没有意义的IndexError,因为肯定有其他的列表在x列表范围内。 在最坏的情况下,因为列表是预定义的(row_2 = [])然后它应该打印“第2道:”,但这甚至不会发生。 谢谢您的帮助!
问题是,正如你所说, row_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()
您还需要在文件的开头添加导入以获取print函数而不是print语句:
from __future__ import print_function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.