当我打印PlyingCard类对象时,它正确返回字符串(例如,十个钻石),但是当我从文件中读取数据时(文本文件:9 d \ n7 d)并将其作为此类的对象添加到列表中,但是如果我想打印此列表的元素,则显示:
回溯(最近一次调用最后一次):文件
" C:/Python34/Zadanka/r10/r10_z11.py" ;,第51行,中
main()File" C:/Python34/Zadanka/r10/r10_z11.py" ;,第50行,在主体上
print(card [0])#TypeError:list indices必须是整数,而不是str文件" C:/Python34/Zadanka/r10/r10_z11.py" ;,第28行, strreturn str(self.ranks [self.rank] +" of" + self.suits [self.suit])
TypeError:list indices必须是整数,而不是str。
class PlayingCard:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.ranks = [None, "Ace", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
self.suits = {"s":"Spades",
"d":"Diamonds",
"c":"Clubs",
"h":"Hearts"}
def getRank(self):
return self.rank
def getSuit(self):
return self.suit
def BJValue(self):
BJVal = 0
if 11 > self.rank > 0:
BJVal = self.rank
elif 14 > self.rank > 10:
BJVal = 10
return BJVal
def __str__(self):
return str(self.ranks[self.rank] + " of " + self.suits[self.suit])
def readCard(filename):
infile = open(filename, 'r')
cards = []
for line in infile:
cards.append(makeCard(line))
infile.close()
return cards
def makeCard(infoStr):
rank, suit = infoStr.split()
return PlayingCard(rank, suit)
def main():
filename = "C:\\Python34\\Zadanka\\r11\\cards.txt"
a = PlayingCard(10, "d")
print(a) # Ten of Diamonds
cards = readCard(filename)
print(cards[0]) # TypeError: list indices must be integers, not str
main()
答案 0 :(得分:2)
在您的makeCard
方法中,您从文件中读取一行并将其拆分,拆分将拆分为两个字符串,以便读取的行不是整数和字符串。
我认为以下应该做的伎俩
return PlayingCard(int(rank), suit)