3 回答

TA贡献1868条经验 获得超4个赞
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))

TA贡献1839条经验 获得超15个赞
您可以使用以下两个选项。
random.choice从列表中选择一个随机元素。
示例代码。
from random import choice
country_dict = [{'capital': 'Andorra la Vella', 'code': 'AD', continent': 'Europe', 'name': 'Andorra', 'timezones': 'Europe/Andorra']},
{'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', ame': 'Afghanistan', 'timezones': ['Asia/Kabul']}
]
country = choice(country_dict)
capital = input("Please enter the captial for country "+country['name'])
if capital == country['capital']:
print("Correct answer")
random.ranint选择 0 和列表长度之间的随机整数。
示例代码:
from random import randint
country_dict = [{'capital': 'Andorra la Vella', 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'timezones': ['Europe/Andorra']},
{'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'timezones': ['Asia/Kabul']}
]
ind = randint(0,len(country_dict)-1)
capital = input("Please enter the captial for country "+country_dict[ind]['name'])
if capital == country_dict[ind]['capital']:
print("Correct answer")

TA贡献1877条经验 获得超1个赞
您可以使用以下方法获取随机样本 randomCountry = random.choice(countries)
但是,如果您多次执行此操作,您可能会多次获得同一个国家/地区。为了解决这个问题,您可以对 10 个不同的元素进行采样randomCountries = random.sample(countries, 10),然后使用它们进行迭代。
请注意,random.sample如果您尝试对比集合中存在的元素更多的元素进行采样,则会引发错误。
因此,您的游戏可能如下所示:
import random
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']},
...
]
rounds = 10
random_countries = random.sample(countries, rounds) # returns 10 random elements (no duplicates)
score = 0
for country in random_countries:
print("Score: %d / %d | Which country has the capital: %s?" % (score, rounds, country['capital']))
country_response = input()
if country_response == country['name']:
score += 1
print("Correct")
else:
print("Incorrect")
添加回答
举报