Python 在字典上使用random.sample时遇到问题

Python 在字典上使用random.sample时遇到问题,python,random,Python,Random,我正在为我的一位老师做一个测验来教她的学生。测验最后将有50多个问题。我找到了random.sample并在代码中实现了它,但它似乎没有效果。尽管我使用的是random.sample,但有时这个问题会在刚接到电话后重复出现。我对Python还很陌生,对此我感到很惊讶 import random # Stores Question, choices and answers questions = { 'What should you do when links appear to

我正在为我的一位老师做一个测验来教她的学生。测验最后将有50多个问题。我找到了random.sample并在代码中实现了它,但它似乎没有效果。尽管我使用的是random.sample,但有时这个问题会在刚接到电话后重复出现。我对Python还很陌生,对此我感到很惊讶

import random
# Stores Question, choices and answers 
questions = {
        'What should you do when links appear to be broken when using the Check Links Site wide command?':  # Q 1
         [' A) Test the link in a browser \n B) Test the link in live view \n C) Check the File path \n D) View Source Code', 'A'],

        'Which 3 combinations of factors encompass usability?':  # Q 2
        [' A) Amount of ads,Load time,Window Size \n B) Load Time,Ease of navigation,Efficiency of use \n C) Server download time, \n D) proper Navigation', 'B'],

        'Which line of html code describes a link to an absolute url using the <A> tag and href attribute?':  # Q 3
        [' A) <A herd = "http://www.acmetoon.org">Acme Toons!</a>, \n B) Herf = "http://www.acmetoon.org">Acme Toons!</a>,'
            '\n C) <A herf = "http://www.acmetoon.org">Acme Toons!</a> \n D) <A herf > = "http://www.acmetoon.org">Acme Toons!</a>', 'A']


        }


print('Dreamweaver Practice test V 1.0')


def pick_question():
        wrong_answers = 0
        while True:
            print()
            # Uses sample to get an item off the dict
            sample_question = random.sample(list(questions.keys()), 3) 
            # Converts the list to a single word ['hello'] -> hello 
            # So no errors complaining about it being it list popup
            new = sample_question[0]
            # Print question and choices 
            print(new)
            print(questions[new][0])
            print()
            user_answer = input('Enter Answer: ')
            print()
            # If the user choice matches the answer
            if user_answer == questions[new][1]:
                print('Correct')
                print()
                print('----Next Question----')
                print()
            elif wrong_answers == 10:
                print('Game Over')
                break
            else:
                print('Wrong')
                print('Correct letter was ' + questions[new][1])
                wrong_answers += 1
                print('Amount wrong ' + str(wrong_answers) + '/10')
                print()
                print('----Next Question----')
                print()


pick_question()
随机导入
#存储问题、选项和答案
问题={
“在使用“检查站点范围内的链接”命令时,如果链接出现断开,您应该怎么做?”:#问题1
['A)在浏览器中测试链接\n B)在实时视图中测试链接\n C)检查文件路径\n D)查看源代码,'A'],
“哪三种因素组合包含可用性?”:#问题2
['A)广告数量、加载时间、窗口大小\n B)加载时间、导航方便性、使用效率\n C)服务器下载时间\n D)正确导航,'B'],
'哪一行html代码使用\n B)Herf=描述指向绝对url的链接http://www.acmetoon.org“>极致卡通!,”
“\n C)顶点卡通!\n D)=”http://www.acmetoon.org“>极致卡通!”,“A”]
}
打印(“Dreamweaver实践测试1.0版”)
def pick_question():
错误答案=0
尽管如此:
打印()
#使用示例从目录中获取项目
sample\u question=random.sample(列表(questions.keys()),3)
#将列表转换为单个单词['hello']->hello
#因此,没有错误抱怨它是它的列表弹出窗口
新建=示例\问题[0]
#打印问题和选项
打印(新)
打印(问题[新增][0])
打印()
用户\答案=输入('输入答案:')
打印()
#如果用户选择与答案匹配
如果用户_answer==问题[new][1]:
打印('正确')
打印()
打印('----下一个问题--')
打印()
elif错误答案==10:
打印(‘游戏结束’)
打破
其他:
打印('错误')
打印('正确的字母是'+问题[新][1])
错误答案+=1
打印(‘金额错误’+str(错误答案)+’/10’)
打印()
打印('----下一个问题--')
打印()
选择问题()

random随机化你的问题列表。先洗牌
,然后像平常一样重复:

...
def quick_questions():
    wrong_answers = 0
    question_keys = list(questions.keys())
    random.shuffle(question_keys) # questions is now in a random order
    for question_key in question_keys:
        new = questions[question_key]
        print()
        # Print question and choices 
        print(new)
        ...

以下内容可能有助于您了解代码真正在做什么,而不是为什么它的行为不符合预期:

import random
# Stores Question, choices and answers 
questions = {'key1': ['text1','ans1'], 'key2': ['text2','ans2'], 'key3':['text3','ans3']}

for i in range (0,10):
    sample_question = random.sample(list(questions.keys()), 3)
    print(sample_question)
其样本输出可能产生:

['key2', 'key3', 'key1']
['key3', 'key1', 'key2']
['key3', 'key1', 'key2']
['key3', 'key1', 'key2']
['key1', 'key2', 'key3']
['key3', 'key2', 'key1']
['key1', 'key3', 'key2']
['key3', 'key2', 'key1']
['key1', 'key3', 'key2']
['key1', 'key2', 'key3']
['key3', 'key1', 'key2']
换句话说,你实际上是在随机挑选一个问题,而不是从你的问题列表中删除这个问题。这就是为什么你有重复。这就像洗一副牌,指向其中一张,然后再洗一次,再指向其中一张——甚至没有从牌堆中移除任何东西


(我知道这并不能真正提供一个“答案”,但你似乎想理解为什么你的代码没有正常运行。杰克的答案很好)

尝试使用random.choice每次你循环
,而True:
循环时,你使用random sample来选择3个随机问题。然后你问这三个问题中的第一个。下次你想问一个问题时,你可以取一个新的样本3并使用第一个。是否打算问3个问题然后停止?@SimeonAleksov已经尝试使用random.choice。这是我的第一个想法。这就是我切换到random.sample的原因。@TomDalton只要用户正确,它就可以继续运行。现在有3个问题,但一旦我修复了这个错误,我将添加超过50个。我只是不想让这些问题重复。1 1 2 3而不是1 3 2或2 3 1-2 1 3希望这对于nobie问题来说是有意义的,但是我应该在我的代码中实现这一点来测试它吗?我厌倦了洗牌,我得到了一个错误。洗牌x[i],x[j]=x[j],x[i]键错误:2@nk001哎呀,对不起。没有意识到
问题
口述
。我已经更新了我的答案。谢谢。经过数小时的搜索,我在尝试将您的代码和我的代码混合在一起时,错误地找到了我要查找的答案D