我想弄清楚为什么会有这个类型的错误。能把整数放在字典里吗?
math_questions = [
{'question1':'1*1',
'answer1':1,
'quote1' :'What you are,you are by accident of birth; what I am,I am by myself.\n There are and will be a thousand princes; there is only one Beethoven.'},
{'question2':'2*1',
'answer2':2,
'quote2': 'Two is company, three is a crowd'},
{'question3': '3*1',
'answer3': 3,
'quote3': 'There are three types of people, those who can count and those who cannot'}
]
# read from a txt file later???
print math_questions[0]['question1']
math_answer = int(raw_input("What is the answer to " + math_questions["question1"] +"? : "))
if math_answer == math_questions['answer1']:
print math_questions['quote']
else:
print "Try again"
print math_questions['answer1'] 这是我得到的错误信息。
PS C:\python27\math_game> python math_game.py
1*1
Traceback (most recent call last):
File "math_game.py", line 17, in <module>
math_answer = int(raw_input("What is the answer to " + math_questions["question1"] +"? : "))
TypeError: list indices must be integers, not str
PS C:\python27\math_game>谢谢你提前帮忙。
发布于 2014-06-01 00:43:07
访问列表时,需要索引。看起来您正在尝试访问一个dict。相反,将:
math_answer = int(raw_input("What is the answer to " + math_questions[0]["question1"] +"? : "))你犯了几个错误:
math_questions["question1"]math_questions["quote"] (我改为math_questions["quote1"])在这里,我们尝试按您使用的方式访问dict的列表。但是,在以这种方式访问它之前,我们需要将它剥离到--仅是的。
>>> obj = [{'data1': 68,
... 'data2': 34,
... 'data3': 79}]
>>> obj['data2']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> obj[0]['data2']
34
>>> 以下是您更新的代码:
math_questions = [
{'question1':'1*1',
'answer1':1,
'quote1' :'What you are,you are by accident of birth; what I am,I am by myself.\n There are and will be a thousand princes; there is only one Beethoven.'},
{'question2':'2*1',
'answer2':2,
'quote2': 'Two is company, three is a crowd'},
{'question3': '3*1',
'answer3': 3,
'quote3': 'There are three types of people, those who can count and those who cannot'}
]
# read from a txt file later???
print math_questions[0]['question1']
math_answer = int(raw_input("What is the answer to " + math_questions[0]["question1"] +"? : "))
if math_answer == math_questions[0]['answer1']:
print math_questions[0]['quote1']
else:
print "Try again"
print math_questions[0]['answer1'] 发布于 2014-06-01 00:52:39
您应该重新设计您的数据结构,类似于以下内容:
class MathQuestion:
def __init__(self, question, answer, quote):
self.question = question
self.answer = answer
self.quote = quote
math_questions = [
MathQuestion(question='1*1', answer='1', quote='What you are …'),
MathQuestion(question='2*1', answer='2', quote='Two is company …'),
#…
]这允许您按以下方式处理字符串:
math_questions[0].answerhttps://stackoverflow.com/questions/23975765
复制相似问题