Python:如何使用类似的运算符来"或" /""列表

时间:2015-08-30 02:47:18

标签: python

我有一个问答程序,询问人们的问题。这些问题存储在 .extend函数中,以将其添加到我的问题列表中。我对每个问题的回答都是如此。

Questions.extend (["Question 1", "Question 2", "Question 3", etc... ])
Answers.extend (["Question 1's Answer", "Question 2's Answer", "Question 3's Answer", etc... ])

这些问题会添加到我的列表中,一次询问一个问题,然后使用多个模块从列表中删除。

那么是否有可能为问题1和其他问题陈述三个或四个可能的答案?因此,如果用户键入问题1中所述的四个答案之一,他们将收到正确的消息。

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的问题。

你最好使用词典。

>>> testbank = {"question 1":["answer1a", "answer1b", "answer1c", "answer1d"],
...  "question n":["answerna", "answernb", "answernc", "answernd"]}
>>> testbank['question 1']
['answer1a', 'answer1b', 'answer1c', 'answer1d']
>>> def validate(answer, question):
...  if answer in testbank['question 1']:
...   print 'Correct!'
...  else:
...   print 'Try again.'
...
>>> answer = "answer1a"
>>> validate(answer, 'question 1')
Correct!
>>> wrongansw = 'foobar'
>>> validate(wrongansw, 'question 1')
Try again.

=========================

代替您对要求的更新,您可以使用列表清单。

>>> answers = [["answer1a", "answer1b", "answer1c", "answer1d"],["answerna", "answernb", "answernc", "answernd"]]
>>> questions = ['question1','questionn']
>>> def validate(a,q):
...  if a in answers[questions.index('question1')]:
...   print 'Correct'
...  else:
...   print 'Try again'
...
>>> validate('foobar','question1')
Try again
>>> validate('answer1a','question1')
Correct
>>> validate('answer1b','question1')
Correct