将用户输入列表与集合列表按重复顺序进行比较

2024-10-02 22:31:21 发布

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

我正在尝试以特定的顺序获取一组答案“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个问题

编辑

再次感谢你的帮助,我能在你的帮助下解决我的问题,还有一些很好的答案。我使用尼克解决方案,因为这是我们学习它的方式。在

我会尝试其他人只是为了适应他们。在


Tags: 答案用户inyou内容列表顺序错误
3条回答

这里没有问题,所以我假设你在问你的问题是什么。在

compare部分在两个列表中使用相同的变量i,但是即使不同,它也不能工作。在

您需要以下几点:

for i in range(len(correctAnswers)):
    correctedList.append(correctAnswers[i] if userAnswersList[i] == correctAnswers[i] else 'XX')

而不是使用:

for i in userAnswersList:

您可能会发现遍历数组并检查值是否相等更容易,例如:

^{pr2}$

这可以使用Python的map方法实现。在

如图中所示:

map(...)
    map(function, sequence[, sequence, ...]) -> list

    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

所以在这种情况下,您需要比较两个相等列表中的每一项,并对它们应用一个条件。我们将介绍的条件将遵循以下逻辑:

如果一个列表中的某个值不等于另一个列表,则设置“XX”,否则返回该值。

因此,我们将在这里引入所谓的“lambda”函数,以满足上述条件。以下是关于lambda是什么的文档:http://www.python-course.eu/lambda.php

^{pr2}$

所以,当我们把它们放在一起时,我们有这样一个:

d = map(lambda x, y: 'XX' if x != y else y, userAnswersList, correctAnswers)

演示:

correctAnswers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']

userAnswersList = ['A', 'C', 'A', 'B', 'D', 'B', 'C', 'A', 'A', 'B', 'A', 'C', 'C', 'A', 'D', 'C', 'D', 'C', 'D', 'B']

结果:

['A', 'C', 'A', 'XX', 'D', 'B', 'C', 'A', 'XX', 'B', 'A', 'XX', 'C', 'A', 'D', 'C', 'XX', 'XX', 'D', 'XX']

相关问题 更多 >