使用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)
答案 0 :(得分:1)
跟进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']
答案 1 :(得分:-1)
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)