Python 3 - 从字典列表中随机打印项目而不重复

时间:2017-11-16 21:47:19

标签: python-3.x list dictionary random

我在测验中使用了一些代码的修改版本,我的问题是我的代码使用random.choice来选择一个测验问题,如何让它仍然随机选择一个问题而不是重复一个问题已经问过用户了吗?

" quiz_data"中的奇怪问题和答案的应用

代码:

def InformationToDictionaries():
quiz_data = [
    {
        "question": "What day is it today?",
        "choices": {"a": "Monday", "b": "Friday", "c": "Wednesday", "d": "Sunday"},
        "answer": "Wednesday")
    },
    {
        "question": "What food am I thinking of?",
        "choices": "Pizza", "b": "Curry", "c": "Pie", "d": "Pasta"},
        "answer": "Curry"
    }
]
return quiz_data


def Quiz():
    score = 0
    for i in range(1,6):
        q = random.choice(quiz_data)
        print("Q." + str(i) + ": ", q.get("question"))
        print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))
        userans = str(input("\n>"))

    if userans == q.get("answer"):
        print("Correct")
        score = score + 1
    else: print("Incorrect")

quiz_data = InformationToDictionaries()
Quiz()

非常感谢您提前回复,如果您对我有任何建议请告诉我,这是我的第一个问题。

--------编辑1 ----------

首次建议后修改代码:

def Quiz():
score = 0
random.shuffle(quiz_data)
for question in quiz_data:
    q = random.choice(quiz_data)
    print("Q." + str("1") + ": ", q.get("question"))
    print('\n'.join("{}: {}".format(x, y) for x, y in q.get("choices").items()))

2 个答案:

答案 0 :(得分:0)

有几种方法。就像在使用它之后从列表中删除问题或者对数组进行洗牌并迭代它一样。

每次挑选时都要从阵列中删除所有问题:

while(len(quiz_data) != 0):
  q = random.choice(quiz_data)
  quiz_data.remove(q)
  #do stuff with q

如果你想迭代一个混洗数组:

from random import shuffle
shuffle(quiz_data)
for question in quiz_data:
  pass #this is only here for the code to run
  #do stuff with question

这两种方式都会以随机顺序为您提供所有问题

答案 1 :(得分:0)

在修改过的代码中,您仍然会在循环中挑选一个随机问题。如果你摆脱了行 block_service = BlockBlobService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY) generator = block_service.list_blobs(CONTAINER_NAME, prefix="trt2", num_results=1000, timeout=60) for blob in generator: path = "temp/" + blob.name.split("/")[-1] block_service.get_blob_to_path(CONTAINER_NAME, blob.name, path, timeout=60) with open(path, 'rb') as f: doc = slate3k.PDF(f) f.close() text_complete = '' for item in doc: item_pat = '' for line in item.split('\n'): item_pat += line + '\n' text_complete += item_pat text_complete = text_complete.strip().lower() if text_complete.find("acórdão") >= 0 and text_complete.find("acordam os magistrados") >= 0: print("Encontrei Acórdão") print("Arquivo "+path) block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Acordao/" + arquivo, path) block_service.delete_blob(CONTAINER_NAME, blob.name) os.remove(path) elif text_complete.find("despacho") >= 0 and text_complete.find("conclusão") < 0 and text_complete.find("embargo") < 0 and \ text_complete.find("ata de audiência") < 0 and text_complete.find("termo de audiência") < 0 and \ text_complete.find("v o t o") < 0 and text_complete.find("certidão") < 0 : print("Encontrei Despacho") print("Arquivo "+path) block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Despacho/" + arquivo, path) block_service.delete_blob(CONTAINER_NAME, blob.name) os.remove(path) elif text_complete.find("sentença") >= 0 and text_complete.find("relatório") >= 0 and \ text_complete.find("acordam") < 0 and text_complete.find("primeira testemunha") < 0 and \ text_complete.find("provas a produzir") < 0 and text_complete.find("embargo") < 0 and \ text_complete.find("voto") < 0: print("Encontrei Sentença") print("Arquivo "+path) block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Sentenca/" + arquivo, path) block_service.delete_blob(CONTAINER_NAME, blob.name) os.remove(path) else: block_service.create_blob_from_path(CONTAINER_NAME, "trt2/Outros/" + arquivo, path) block_service.delete_blob(CONTAINER_NAME, blob.name) os.remove(path) 并在循环体中使用q = random.choice(quiz_data)变量,你可以按洗牌顺序取它们。

question