简体   繁体   中英

random.choice without duplicates in tuple in python

I'm making a simple translation game, and I don't want duplicate "quiz" when I run this code.

Here is my current code that asks duplicate questions:

sentence = ("naranja", "azul", "llamada", "blanco", "negro", "cancion", "rojo", "hielo", "cara")

answer = ("orange", "blue", "call", "white", "black", "sing", "red", "ice", "face")

num = 0

while num <= len(sentence):
    quiz = random.choice(sentence)
    order = sentence.index(quiz)
    print(quiz)
    a = input("Translate in English : ")
    if a == answer[order]:
        print("Correct!")

    else :
        print("Wrong!", answer[order])

The clean way to do it is to avoid manipulating indices as much as possible.

You can get pairs of (question, answer) using zip , then use random.shuffle to shuffle this list, and you just have to iterate on them:

from random import shuffle


sentence = ("naranja", "azul", "llamada", "blanco", "negro", "cancion", "rojo", "hielo", "cara")
answer = ("orange", "blue", "call", "white", "black", "sing", "red", "ice", "face")

associations = list(zip(sentence, answer))
shuffle(associations)

for quiz, answer in associations:
    print(quiz)
    a = input("Translate in English : ")
    if a == answer:
        print("Correct!")
    else :
        print("Wrong!", answer)

Try using the random sample function. This can be used to give you a randomized list of n elements from a given list without duplicates. Here you can take a sample with a size of the length of the questions and then iterate over the quiz questions:

import random

sentence = ("naranja", "azul", "llamada", "blanco", "negro", "cancion", "rojo", "hielo", "cara")

answer = ("orange", "blue", "call", "white", "black", "sing", "red", "ice", "face")

num = 0

# Get a randomly ordered list of the questions
quiz_questions = random.sample(sentence, len(sentence))

# Iterate over the random list
for quiz in quiz_questions:
    order = sentence.index(quiz)
    print(quiz)
    a = input("Translate in English : ")
    if a == answer[order]:
        print("Correct!")

    else :
        print("Wrong!", answer[order])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM