List Python字典类型

List Python字典类型,list,python-2.7,types,List,Python 2.7,Types,我正试图弄明白为什么会出现这种类型的错误。可以把整数放在字典里吗 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.'

我正试图弄明白为什么会出现这种类型的错误。可以把整数放在字典里吗

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>
PS C:\python27\math\u game>python math\u game.py
1*1
回溯(最近一次呼叫最后一次):
文件“math_game.py”,第17行,在
math_answer=int(原始输入(“什么是“+数学问题[“问题1”]+”?:”)的答案)
TypeError:列表索引必须是整数,而不是str
PS C:\python27\math\u game>

提前感谢您的帮助。

当您访问列表时,您需要索引。看起来您正在尝试访问一个
dict
。相反,把:

math_answer = int(raw_input("What is the answer to " + math_questions[0]["question1"] +"? : "))
您有一些错误:

  • 您在第17、19、20、23行有
    数学问题[“问题1”]
  • 你的
    数学问题[“quote”]
    根本不存在(我改为
    数学问题[“quote1”]
  • 在这里,我们尝试通过您使用的方式访问
    dict
    s列表。但是,我们需要将其剥离到只有
    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
    >>> 
    

    您应该修改数据结构,如下所示:

    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].answer
    
    math_questions[0].answer