我正在尝试以特定的顺序获取一组答案“a”、“B”、“C”或“D”,例如选择题,并让用户输入答案。之后我希望它创建第三个列表,并打印出正确和错误的内容。这是我到目前为止的情况。在
userAnswersList = []
correctAnswers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']
while len(userAnswersList) <= 19:
userAnswers = input('Give me each answer total of 20 questions I\'ll let you know how many you missed.')
userAnswersList.append(userAnswers.upper())
correctedList = []
for i in userAnswersList:
if i in correctAnswers:
correctedList.append(i)
else:
correctedList.append('XX')
print(correctedList)
因此,我的最终结果将是正确的列表,其中他们错过了答案,如果它是正确的,它只是把用户的输入放在那个位置。 用户在输入20个答案后会这样看 ['A'、'C'、'A'、'XX'、'D'、'B'、'C'、'XX'、'C'、'B'、'A'、'XX'、'A'、'D'、'XX'、'B'、'XX'、'A'] 如果他们按顺序漏掉了5个问题
编辑
再次感谢你的帮助,我能在你的帮助下解决我的问题,还有一些很好的答案。我使用尼克解决方案,因为这是我们学习它的方式。在
我会尝试其他人只是为了适应他们。在
这里没有问题,所以我假设你在问你的问题是什么。在
compare部分在两个列表中使用相同的变量i,但是即使不同,它也不能工作。在
您需要以下几点:
而不是使用:
您可能会发现遍历数组并检查值是否相等更容易,例如:
^{pr2}$这可以使用Python的map方法实现。在
如图中所示:
所以在这种情况下,您需要比较两个相等列表中的每一项,并对它们应用一个条件。我们将介绍的条件将遵循以下逻辑:
如果一个列表中的某个值不等于另一个列表,则设置“XX”,否则返回该值。
因此,我们将在这里引入所谓的“lambda”函数,以满足上述条件。以下是关于lambda是什么的文档:http://www.python-course.eu/lambda.php
^{pr2}$所以,当我们把它们放在一起时,我们有这样一个:
演示:
结果:
相关问题 更多 >
编程相关推荐