我正在尝试使用python制作纸牌游戏。我在下面有一个文本文件,它是卡ID,卡名称,卡描述和卡命中点。
1, Medusa, Feel The Wraith, 98
2, Gigle , See Him See Him, 54
3, Brozi , Pinch an inch, 91
下面我有一些python。我有这个python类,只是一张卡片。我想要做的是在这些卡片(类对象)的卡片组(列表)中进行操作。这是我要尝试执行的一些代码,该代码将读取文本文件并将其放入对象中,然后放入列表中。
import sys
import os
class Card:
def__init__(self, card_id, name, desc, hp):
self.card_id = card_id
self.name = name
self.desc = desc
self.hp = hp
self.cards = []
deck = []
fh = open('dets.txt').readlines()
for line in fh:
row = line.split(',')
card_id, name, desc, hp = [i.strip() for i in row]
card = deck.get(card_id, Card(card_id, name, desc, hp))
deck[card_id] = card
我在赛道上吗?我对Python比较陌生。谢谢
答案 0 :(得分:2)
如果只想将这些卡片对象放在列表中,请执行以下操作:
deck = []
fh = open('dets.txt').readlines()
for line in fh:
row = line.split(',')
card_id, name, desc, hp = [i.strip() for i in row]
card = Card(card_id, name, desc, hp)
deck = deck + [ card ]
否则,通过查看代码,我想您要将它们存储在card_id
为key
的字典中。要将它们存储在字典中,
deck = {} #dictionary
fh = open('dets.txt').readlines()
for line in fh:
row = line.split(',')
card_id, name, desc, hp = [i.strip() for i in row]
card = Card(card_id, name, desc, hp)
deck[card_id] = card #'card_id' is the 'key' and 'card' is 'value'
要打印字典中的卡片名称,请使用for-loop
,
for each_key in deck:
print(each_key, " - ", deck[each_key].name )
这将给出输出:
1 - Medusa
2 - Gigle
3 - Brozi
答案 1 :(得分:0)
设为底部:
deck = []
with open('dets.txt') as fh:
for line in fh:
row = line.strip().split(', ')
deck.append(Card(*row))
答案 2 :(得分:0)
您正在使用列表,它没有任何获取方法。 尝试使用字典
它将帮助您检索类对象
例如。
myDict = {card_id1 : CardObject1, card_id2 : CardObject2, ....}
因此,当您要获取卡片对象时,只需键入此
if card_id in myDict.keys():
myDict(card_id)
答案 3 :(得分:0)
通过执行以下操作,可以大大简化代码,并使其更加Python化:
with open('dets.txt') as f
来读取文件。您应该在打开文件时关闭它,并且此上下文管理器允许您在读取文件时关闭它。因此,您可以使用以下代码:
import sys
import os
class Card:
def__init__(self, card_id, name, desc, hp):
self.card_id = card_id
self.name = name
self.desc = desc
self.hp = hp
self.cards = []
deck = []
with open('dets.txt') as f:
for line in f:
args = line.strip().split(', ')
args[0] = int(args[0])
args[-1] = int(args[-1])
deck.append(Card(*args))
您可以使用dataclases
来简化类定义,如下所示:
@dataclass
class Card:
card_id: int
name: str
desc: str
hp: int