簡體   English   中英

我將如何實現random.sample,以便它在不重復的情況下從3個變量中選擇2個?

[英]How would i implement random.sample so that it would choose 2 out of 3 variables without it repeating?

我正在做一個使用類和OOP的迷你測驗。 我想讓代碼從3個問題中隨機選擇2個,但我不知道是否應該使用random.sample或在哪里使用它。

import random

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

question_prompts = ['What is the capital of England? (a) London (b) Liverpool (c) Glasgow.  Answer(Type a, b or c): ', 'What is the capital of France? (a) Callais (b) Paris (c) Bologne. Answer(Type a, b or c): ', 'What is the capital of Netherlands? (a) Amsterdam  (b) Tilburg (c) Eindhoven. Answer(Type a, b or c): ',]


questions[Question(question_prompts[0], 'a'), Question(question_prompts[1], 'b'), Question(question_prompts[2], 'a'),]


def run(questions):
    score = 0
    answer = (questions)
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
            print('correct!')

我想要它,以便代碼從3個問題中隨機選擇2個,而無需重復。

使用random.sample()函數。

for question in random.sample(questions, 2):

您可以使用numpy.random.choice

>>> import numpy as np
>>> set_of_options = [1, 2, 3, 4, 5]
>>> np.random.choice(a=set_of_options, size=2, replace=False)
array([2, 3])
>>> np.random.choice(a=set_of_options, size=2, replace=False)
array([5, 1])
>>> np.random.choice(a=set_of_options, size=2, replace=False)
array([1, 2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM