raw_input,词典和类

时间:2014-09-30 07:00:32

标签: python python-2.7 dictionary

在Python 2.7中,我试图在用户输入名称时尝试这样做,它会搜索该名称是否在预定义的字典中,如果是,则使用类创建一个对象并使用字典的值。到目前为止,这是我的代码:

import os

weaponList = {
'axe': {'Name': 'axe', 'Mass': 1500, 'Strike': 'Chop'},
'knife': {'Name': 'knife', 'Mass': 300, 'Strike': 'Cut'},
'club': {'Name': 'club', 'Mass': 2000, 'Strike': 'Blunt'},
'stone': {'Name': 'stone', 'Mass': 800, 'Strike': 'Blunt'},
}

class meleeWeapon:
    def __init__(self, name, mass, strike):
        self.name = name
        self.mass = mass
        self.strike = strike

def weaponask():
    wepn = raw_input("Use knife, club, axe, or stone?\n> ").lower()
    if wepn in weaponList:
        currentWeapon = meleeWeapon(wepn['Name'], wepn['Mass'], wepn['Strike'])
        print "success"
    else:
        print "item not recognized"
        weaponask()
    #return wep

weaponask()

os.system('pause')

但是,当我尝试运行此代码时,出现以下错误:

Use knife, club, axe, thrown stone, slung stone, or firearm?
> axe
Traceback (most recent call last):
  File "C:\Python\dict.py", line 30, in <module>
    weaponask()
  File "C:\Python\dict.py", line 23, in weaponask
    currentWeapon = meleeWeapon(wepn['Name'], wepn['Mass'], wepn['Strike'])
TypeError: string indices must be integers, not str


Press any key to continue . . .

知道我做错了什么吗? TIA

2 个答案:

答案 0 :(得分:1)

wepn是用户输入的字符串。在您的情况下可以是"knife", "club", "axe" or "stone"。您需要改为使用weaponList

例如,weaponList["Knife"]会为您提供{'Name': 'knife', 'Mass': 300, 'Strike': 'Cut'}

替换它:

currentWeapon = meleeWeapon(wepn['Name'], wepn['Mass'], wepn['Strike'])

用这个:

currentWeapon = meleeWeapon(weaponList[wepn]['Name'], weaponList[wepn]['Mass'], weaponList[wepn]['Strike'])

<强>更新

你可以像评论中的jonrsharpe一样建议(看起来也更干净!)

currentWeapon = meleeWeapon(**weaponList[wepn])

答案 1 :(得分:0)

将您当前的武器更改为:

currentWeapon = meleeWeapon(weaponList[wepn]['Name'],weaponList[wepn]['Mass'],weaponList[wepn]['Strike'])

因为wepn是weaponList的关键,用于访问wepn的数据所以首先你应该访问wepn(weaponList [wepn])。