[Solved] Python: How to use a similar operator to “or”/”in” in a list [closed]


I’m not sure if I understand your question correctly.

You maybe better off using a dict.

>>> 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.

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

In lieu of your update on the requirement, you can use list of lists.

>>> 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

4

solved Python: How to use a similar operator to “or”/”in” in a list [closed]