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

时间:2016-12-07 22:24:17

标签: python random

我正在为我的老师做一个测验,教她的学生。测验最后会有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()

2 个答案:

答案 0 :(得分:1)

首先使用random.shuffle随机化您的问题列表,然后正常迭代:

...
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)
        ...

答案 1 :(得分:0)

以下内容可以帮助您了解您的代码实际上在做什么,而不是为什么它没有按预期运行:

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']

换句话说,您实际上是在随机选择一个问题,但不会从问题列表中删除问题。这就是你重复的原因。这就像是在拖着一副卡片,指着一张卡片,然后又一次拖着它再指向其中一个 - 甚至没有从卡片上移走任何东西。

(我知道这并没有真正提供“答案”,但你似乎想要理解为什么你的代码没有表现。杰克的答案非常好)