字典列表中的随机键值

2024-06-13 00:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python的新手

我有一个列表,满是字典,上面有国家的名字和它们的首都,从列表中我想随机地从国家抓取键值,显示一个问题,“澳大利亚的首都是什么?然后,我想从我的列表中随机选择另外两个大写字母,以及正确的答案,洗牌它们,让用户选择他们的选择。我有一个非常粗略的想法。我对印刷和要求输入什么都没意见。主要的问题是,我怎么做的答案列表,包括正确的答案,加上两个随机答案。我希望你能从下面看到我在做什么。你知道吗

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)

Tags: 答案列表字典onrandom大写字母国家名字
2条回答
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)

继pvgs注释之后,在本例中使用稍微不同的数据结构可能会更清楚一些

import random

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

这样你就可以直接访问一个国家的资本:pool["France"]产生Paris。你知道吗

从可用国家名称列表中随机选择一个国家,并将正确答案添加到列表中:

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

然后用不同的错误答案填写清单:

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

最后随机排列顺序:

random.shuffle(answerList)

结果的一个例子是:

>>> print(randomCountry, answerList)
Thailand ['London', 'Bangkok', 'Paris']

相关问题 更多 >