我必须编写测验作为作业分配。最后一步涉及到我随机询问问题的顺序。
我不确定如何执行此操作,因为即使我现有的代码也无法100%确认-是从CSV文件本身还是从列表/字典中选择它(是列表还是字典?)。
score=0
questionno=0
def parse_csv(file_name: str) -> dict:
retval = {}
with open(file_name) as f:
for line in f:
data = line.strip().split(',')
key, *values = (v.strip() for v in data)
retval[key] = values
return retval
questions = parse_csv('questions.txt')
for question, answers in questions.items():
questionno+=1
correct = answers[-1]
answers = answers[:-1]
print(questionno)
result = input(f"{question}: {','.join(answers)}")
if result=="A" or result=="B" or result=="C" or result=="D":
if result == correct:
print('Correct!')
score+=1
else:
print(f'The correct answer is {correct!r}')
break
else:
print("Invalid Entry")
break
print(score)
答案 0 :(得分:0)
根据设计,Python中的字典没有任何顺序(有关说明,请参见OrderedDict),但是当您对其进行迭代时,该顺序也不是真正随机的!
以下是我建议使问题顺序真正随机的内容:
VersionNumber("2.12.5").matchesSemVer(SemanticSelector(">=2.12"))
这个想法是列出(问题,答案)元组的列表,使用random.shuffle对其进行混洗,然后对其进行迭代。
编辑:我忘记了shuffle()到位并且没有返回列表,现在它应该可以工作了
答案 1 :(得分:0)
这是一本字典。将字典转换为元组列表后,可以使用numpy.random.shuffle,如下所示:
import numpy as np
questions = list(parse_csv('questions.txt').items())
np.random.shuffle(questions)
for question, answers in questions:
...
答案 2 :(得分:0)
如果用户输入的条目无效,您可以再次询问该问题-还会拖延订单。
import random
score=0
questionno=0
def parse_csv(file_name: str) -> dict:
retval = {}
with open(file_name) as f:
for line in f:
data = line.strip().split(',')
key, *values = (v.strip() for v in data)
retval[key] = values
return retval
questions = parse_csv('questions.txt')
l = list(questions.items())
random.shuffle(l)
questions = dict(l)
for question, answers in questions.items():
questionno+=1
correct = answers[-1]
answers = answers[:-1]
while True:
result = input(f"{question}: {','.join(answers)}")
if result=="A" or result=="B" or result=="C" or result=="D":
if result == correct:
print('Correct!')
score+=1
break
else:
print(f'The correct answer is {correct!r}')
break
else:
print("Invalid Entry\n Try again...")