在Python 2.7中,我試圖讓用戶輸入一個名稱,它會搜索以查看該名稱是否在預定義字典中,然後如果是,則創建一個對象使用一個類並使用字典的值。這裏是我到目前爲止的代碼:raw_input,字典和類
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
嘗試將'wepn ['Name']'更改爲'weponList ['Name']'? – fredtantini 2014-09-30 07:02:26
'weaponList'對於不是列表的結構來說名字很差。而且,你可以將'meleeWeapon'實例直接放入字典中,而不是屬性的子元素。 – jonrsharpe 2014-09-30 07:15:37