检查项目在一个列表中的位置到另一个列表

2024-06-09 09:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个琐事游戏,唯一的问题是我很难找到正确的答案。这是我回答其中一个问题的代码

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)

我试图通过检查列表中的位置来检查用户对问题2的回答是否是对问题2的回答,而不是对问题4的回答。你知道吗


Tags: 答案代码游戏inputifpositionrandomyes
2条回答

您可以使用namedtuple作为数据容器。你知道吗

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)

简单的解决方案是为作业使用正确的数据类型。你知道吗

例如,如果你的mylist是一个(question, answer)对的列表,而不是有两个单独的列表

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

或者,用字典代替列表:

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]

为什么口授更好?首先,对于列表,您必须反复搜索列表以找到所需的值,例如,mylist.remove从开始处开始,将每个元素与您的值进行比较,直到找到正确的值为止。除了速度慢和过于复杂之外,如果您可能有重复的值(例如,尝试a = [1, 2, 3, 1],然后value = a[0],然后a.remove(value)然后看看会发生什么…),那么这也是错误的。你知道吗


但是,如果您不能更改数据结构,则可以随时使用zip将一对单独的列表压缩为一对单独的列表:

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)

相关问题 更多 >