我是一个非常新手的学习者,我正在上Python课来学习。 这个问题与课程无关,只是与我在上课时正在处理的一个项目有关(我正在开发一个简单的游戏,使用我在课堂上学到的概念来更新、扩展和清理我的代码。
我目前正在学习元组、列表和字典,并认为简单的元组会清除很多 IF 语句并简化代码。 但是,我无法让它完全按照我希望的方式工作。
基本上,我为所有类都有一组元组(注意,这些是训练分类,而不是 Python 类)。 它们有不同的数字,然后我有一个元组,其中包含所有类的名称列表。 在代码中的某个时刻,我要求用户输入以确定字符的类。 我希望能够使用该输入,以便我可以从元组中提取(正确的术语拼接吗?)值,例如我想将元组第三个位置的任何值添加到另一个值。 现在我无法将用户输入与同名元组相关联。 有没有办法做到这一点?
# Class list
Apprentice = (6, 0, 0, 0, 0, 0, 0)
Warrior = (12, 2, 0, 2, 0, 0, 0)
Paladin = (14, 2, 0, 2, 1, 0, 1)
Barbarian = (12, 6, 0, 3, -1, -1, -1)
Blademaster = (10, 4, 4, 0, 0, 0, 0)
Assassin = (8, 0, 8, -2, 0, 0, 0)
Rogue = (8, 0, 4, 0, 0, 0, 0)
Monk = (10, 2, 2, 2, 2, 2, -4)
Bard = (8, 0, 0, 0, 0, 0, 4)
Mage = (6, 0, 0, 0, 2, 2, 0)
Priest = (6, 0, 0, 0, 1, 2, 1)
Wizard = (4, -2, -2, -2, 6, 8, 0)
Scholar = (6, -1, -1, 0, 4, 4, 0)
Necromancer = (6, 0, 0, 0, 6, 6, -5)
classList = ('Apprentice', 'Warrior', 'Priest', 'Mage', 'Wizard', 'Rogue', 'Bard', 'Paladin', 'Scholar', 'Necromancer', 'Barbarian', 'Blademaster', 'Assassin', 'Monk')
validClass = False
while validClass == False:
charClass = raw_input('What type of training have you had (Class)? ')
if charClass in classList:
print ''
validClass = True
else:
print 'That is not a valid class.'
您可以通过访问全局变量列表来执行此操作,但我建议不要这样做。更好的方法是创建类字典,如下所示:
classes = {'Apprentice':Apprentice,'Warrior':Warrior, ...}
然后做类似的事情
selected_class = None
while True:
charClass = raw_input('What type of training have you had (Class)? ')
if charClass in classes:
selected_class = classes[charClass]
break
else:
print 'That is not a valid class.'
你应该使用 dict
my_class = dict(
Apprentice=(6, 0, 0, 0, 0, 0, 0),
Warrior=(12, 2, 0, 2, 0, 0, 0),
Paladin=(14, 2, 0, 2, 1, 0, 1),
Barbarian=(12, 6, 0, 3, -1, -1, -1),
Blademaster=(10, 4, 4, 0, 0, 0, 0),
Assassin=(8, 0, 8, -2, 0, 0, 0),
Rogue=(8, 0, 4, 0, 0, 0, 0),
Monk=(10, 2, 2, 2, 2, 2, -4),
Bard=(8, 0, 0, 0, 0, 0, 4),
Mage=(6, 0, 0, 0, 2, 2, 0),
Priest=(6, 0, 0, 0, 1, 2, 1),
Wizard=(4, -2, -2, -2, 6, 8, 0),
Scholar=(6, -1, -1, 0, 4, 4, 0),
Necromancer=(6, 0, 0, 0, 6, 6, -5),
)
while 1:
try:
val = my_class[raw_input('What type of training have you had (Class)? ')]
break
except KeyError:
print 'That is not a valid class.'
最好使用字典,但如果它是作业并且不允许使用字典,则可以执行以下操作:
validClass = False
while validClass == False:
charClass = raw_input('What type of training have you had (Class)? ')
if charClass in classList:
print eval(charClass)
validClass = True
else:
print 'That is not a valid class.'
eval
函数允许您在自身内运行 python 代码。同样,最好使用字典。
使用字典要好得多,但如果不允许这样做,则可以使用 vars()
函数,该函数返回所有全局值的字典。
while validClass == False:
try:
vals = vars()[raw_input('What type of training have you had (Class)? ')]
except KeyError:
print 'That is not a valid class.'
尝试将每个变量与字符名称的字符串一起存储在字典中,而不是创建单独的元组。现在不可能将你的 ClassList 与统计信息链接起来,因为每个类的变量名无法与每个类的字符串名进行比较(你必须将一个字符串与另一个字符串进行比较)。
如果您以前没有使用过词典,请尝试学习。我认为在这种情况下会非常有帮助!
http://www.tutorialspoint.com/python/python_dictionary.htm