gpt4 book ai didi

Python 3 : How do I make a game using user input and retrieving answer from a list of dictionaries, 然后用点系统?

转载 作者:太空宇宙 更新时间:2023-11-04 06:43:27 25 4
gpt4 key购买 nike

我正在尝试制作一款游戏,要求用户根据从字典列表中随机选择的首都猜测一个国家(类似于底部的链接)。

一共猜10个国家,猜对得1分,共10分。

我导入了一个变量“countries”,其中包含如下字典列表:

[{'capital': 'Andorra la Vella',
'code': 'AD',
'continent': 'Europe',
'name': 'Andorra',
'timezones': ['Europe/Andorra']},
{'capital': 'Kabul',
'code': 'AF',
'continent': 'Asia',
'name': 'Afghanistan',
'timezones': ['Asia/Kabul']},

那么如何根据特定键名打印随机选择呢?在这种情况下,任何词典中的任何“首都”。

Python-Dictionary states and capital game

最佳答案

random.choice 非常适合这个用例:)

import random


country_dlist = [{'capital': 'Andorra la Vella',
'code': 'AD',
'continent': 'Europe',
'name': 'Andorra',
'timezones': ['Europe/Andorra']},
{'capital': 'Kabul',
'code': 'AF',
'continent': 'Asia',
'name': 'Afghanistan',
'timezones': ['Asia/Kabul']}
]

def run():
tot_points = 0
num_of_ques = len(country_dlist)
for i in range(num_of_ques):
choice = random.choice(country_dlist)
que = country_dlist.remove(choice)
capital = raw_input("Please enter the captial for country {}: ".format(choice['name']))
if capital.lower() == choice['capital'].lower(): # case insensitive match :)
tot_points += 1
return tot_points

points = run()
print("You scored {} points".format(points))

关于Python 3 : How do I make a game using user input and retrieving answer from a list of dictionaries, 然后用点系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com