简体   繁体   中英

checking the position of an item in one list to another list

I am trying to make a trivia game, the only problem is I am having a hard time checking for the right answer. Here is my code for one of the questions

Question2 = random.choice(mylist)
print (Question2)
Userinput = input()
if(Question2.position == Question2answer.position):
    print('Yes, that is correct!')
else:
    print('Sorry, wrong answer')
mylist.remove(Question2)

I am trying to check if what the user put for question 2 was the answer to question 2 and not 4 by checking the positions in the list.

The easy solution is to use the right data type for the job.

For example, if your mylist were a list of (question, answer) pairs, instead of having two separate lists;

Question2, Answer2 = random.choice(mylist)
print(Question2)
Userinput = input()
if Userinput == Answer2:
    print('Yes, that is correct!')
else:
    print('Sorry, wrong answer')
mylist.remove((Question2, Answer2))

Or, alternatively, with a dictionary instead of a list:

Question2 = random.choice(mydict)
print(Question2)
Userinput = input()
if Userinput == mydict[Question2]:
    print('Yes, that is correct!')
else:
    print('Sorry, wrong answer')
del mylist[Question2]

Why is a dict better? Well, for one thing, with a list, you have to repeatedly search through the list to find the value you want—eg, mylist.remove starts at the beginning and compares each element to your value until it finds the right one. Besides being slow, and overly complicated, this does the wrong thing if you can ever have duplicate values (eg, try a = [1, 2, 3, 1] , then value = a[0] , then a.remove(value) and see what happens…).


But if you can't change the data structures, you can always use zip to zip up a pair of separate lists into a single list of pairs on the fly:

Question2, Answer2 = random.choice(zip(mylist, myanswers))
print(Question2)
Userinput = input()
if Userinput == Answer2:
    print('Yes, that is correct!')
else:
    print('Sorry, wrong answer')
mylist.remove(Question2)
myanswers.remove(Answer2)

You could use namedtuple as data container.

from collections import namedtuple
import random


Question = namedtuple('Question', ['question', 'answer'])
questions = [
    Question('Question 1', 'Answer 1'),
    Question('Question 2', 'Secret'),
    Question('Question 3', '3'),
]


q = random.choice(questions)
print("%s ?" % q.question)
user_input = raw_input().strip()


if(q.answer == user_input):
    print('Yes, that is correct!')
else:
    print('Sorry, wrong answer')

questions.remove(q)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM