来自与Python中的用户输入同名的元组的值(我很难解释,如果我能找到更好的方式来表达我自己,我会更新标题)

2024-05-14 02:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个非常初级的学习者,我正在参加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.'

Tags: 代码用户paladinclass课程元组monkrogue
3条回答

你应该使用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.'

最好使用字典,但如果是作业,不允许使用dicts,则可以执行以下操作:

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代码。再说一次,最好用字典。你知道吗

您可以通过访问全局变量列表来实现这一点,但是我建议不要这样做。更好的方法是创建一个类字典,如下所示:

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.'

相关问题 更多 >