简体   繁体   English

词典列表中的随机键值

[英]Random key values from list of dictionaries

New to using Python 使用Python的新手

I have a list, full of dictionaries with country names and their capitals, from the list I want to randomly grab the key value from country, display a question, "What is the capital of Australia? I then want to randomly select two other capitals from my list, as well as the correct answer, shuffle them and get the user to select their choice. I have a VERY rough Idea. I'm fine with print and asking for input and all that. The main issue is, how do I make the list of answers to include the correct answer, plus the two random answers. I hope from what is below you can see what I'm trying to do. 我有一个列表,上面有字典,上面有国家名称和首都,我要从列表中随机获取关键值,并显示一个问题:“澳大利亚的首都是什么?然后我想随机选择另外两个首都从我的列表中以及正确的答案中,将它们打乱,然后让用户选择他们的选择。我有一个非常粗略的想法。我可以打印并要求输入内容,主要是,如何做。我列出了包含正确答案以及两个随机答案的答案列表,希望从下面的内容中可以看到我正在尝试做的事情。

Alist = [{country": "Australia", "capital": "Canberra"} {country": "UK", "capital": "London"}.....] #list goes on

AnswerList[ ]

randomCountry = random.choice(Alist, ['country'])

randomAnswers = random.sample(Alist, ['capital'], 2)

AnswerList.append (randomAnswers) #not sure on how to get the correct answer in here

random.shuffle(AnswerList)

Following up on pvgs comment, using a slightly different data structure may be a little bit clearer in this case 跟踪pvgs注释,在这种情况下,使用稍微不同的数据结构可能会更清楚一些

import random

pool={"Australia":"Canberra",
      "United Kingdom":"London",
      "Germany":"Berlin",
      "France":"Paris",
      "Brasil":"Brasília",
      "Thailand":"Bangkok"}
totalAnswersOffered=3

This way you can directly access the capital of a country: pool["France"] yields Paris . 这样,您可以直接访问一个国家的首都: pool["France"]产生Paris

Select a random country from the list of available country names and add correct answer to a list: 从可用国家名称列表中选择一个随机国家,然后将正确答案添加到列表中:

randomCountry = random.choice(list(pool.keys()))
answerList = [pool[randomCountry]]

Then fill the list with different, wrong answers: 然后用不同的错误答案填充列表:

while len(answerList)<totalAnswersOffered:
    randomAnswer = random.choice(list(pool.values()))
    if randomAnswer not in answerList:
        answerList.append(randomAnswer)

And finally randomize the order: 最后随机化顺序:

random.shuffle(answerList)

An example of the result would be this: 结果的示例如下:

>>> print(randomCountry, answerList)
Thailand ['London', 'Bangkok', 'Paris']
right = Alist[<rightKey>]

AnswerList.append(right)

wrong = list(Alist.keys())
wrong.remove(<rightKey>)

for key in random.sample(wrong, 2):
    AnswerList.append(Alist[key])

random.shuffle(AnswerList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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