【发布时间】:2018-04-30 13:56:17
【问题描述】:
我有一些我在测验中使用的代码的修改版本,我的问题是我的代码正在使用 random.choice 来选择一个测验问题,我如何让它仍然随机选择一个问题但也不重复一个问题已经向用户询问过?
对“quiz_data”中奇怪的问题和答案表示歉意
代码:
def InformationToDictionaries():
quiz_data = [
{
"question": "What day is it today?",
"choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
"answer": "Wednesday")
},
{
"question": "What food am I thinking of?",
"choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
"answer": "Curry"
}
]
return quiz_data
def Quiz():
score = 0
for i in range(1,6):
q = random.choice(quiz_data)
print("Q." + str(i) + ": ", q.get("question"))
print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
userans = str(input("\n>"))
if userans == q.get("answer"):
print("Correct")
score = score + 1
else: print("Incorrect")
quiz_data = InformationToDictionaries()
Quiz()
非常感谢您提前回复,如果您对我有任何建议,请告诉我,这是我的第一个问题。
--------编辑1---------
第一次建议后修改代码:
def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
q = random.choice(quiz_data)
print("Q." + str("1") + ": ", q.get("question"))
print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
【问题讨论】:
-
quiz_data(顶部的那个)是一个列表,而不是字典。您可以随机播放该列表并按顺序回答问题,以确保不会重复。 -
@BilltheLizard 所以我使用 random.shuffle?然后按顺序打印项目?我的问题是我仍然想按随机顺序提问。
-
是的,在循环之前打乱它们,然后在循环内打印它们(摆脱对
random.choice的调用)。 -
@BilltheLizard as Joaquim Ferrer 也提到我已经尝试过这种方法,虽然发现问题确实是随机顺序的,但我仍然得到重复?
-
请贴出您现在正在使用的代码。
标签: python python-3.x list dictionary random