[英]How to choose a random question from items in a list/dict imported from a CSV file?
我必須將測驗編碼為作業。 最后一步涉及到我隨機選擇問題的順序。
我不確定如何執行此操作,因為即使我現有的代碼也無法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)
按照設計,Python中的字典沒有任何順序(請參閱OrderedDict ),但是當您對其進行迭代時,該順序也不是真正隨機的!
我建議將問題順序真正隨機化:
from random import shuffle
questions = parse_csv('questions.txt')
shuffledquestions = list(questions.items())
shuffle(shuffledquestions)
for (question, answer) in shuffledquestions:
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
這個想法是列出(問題,答案)元組的列表,使用random.shuffle對其進行混洗,然后對其進行迭代。
編輯:我忘記了shuffle()到位並且沒有返回列表,現在應該可以了
這是一本字典。 在將字典轉換為元組列表后,可以使用numpy.random.shuffle ,如下所示:
import numpy as np
questions = list(parse_csv('questions.txt').items())
np.random.shuffle(questions)
for question, answers in questions:
...
如果用戶輸入的條目無效,您可以再次詢問該問題-也會使訂單混亂。
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...")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.