[英]random.choice without duplicates in tuple in python
我正在制作一个简单的翻译游戏,我不想在运行此代码时重复“测验”。
这是我当前提出重复问题的代码:
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])
干净的方法是尽可能避免操纵索引。
您可以使用zip 获得成对的(问题,答案),然后使用 random.shuffle随机播放此列表,您只需对其进行迭代:
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)
尝试使用随机sample
function。 这可用于为您提供来自给定列表的 n 个元素的随机列表,而不会重复。 在这里,您可以抽取一个大小与问题长度相同的样本,然后遍历测验问题:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.