【发布时间】:2017-11-06 16:03:48
【问题描述】:
在我的 .csv 文件中,我总共有 12 个国家(有 12 个首都),但是我想从这 12 个国家中随机选择 10 个。
我从 stackoverflow 资源中发现了一些单项或成对选择,但不是从字典中随机选择 10 个项目。我该怎么做?
这是我在国家和首都考试中的相关代码,用户将首都输入到所询问的国家,并输出正确或不正确的答案。
#Defining the function of reading .csv file from path into dictionary
def readCsvIntoDictionary(path):
dic = {}
with open(path, 'r', newline='') as f:
reader = csv.reader(f)
for row in reader:
dic[row[0]] = row[1];
return dic;
count = 0;
# for loop with key variable definition in dic
for key in dic:
# ans variable defined for user input
ans = input('What is the capital of ' + key + '?\n')
# User can input lower and upper answers
if(ans.lower() == dic[key].lower()):
# key lookup in dic (dictionary) if answer is correct at end of the loop
dic[key] = 'Correct! ' + dic[key] + ' is the capital of ' + key;
count = count + 1;
else:
# key lookup in dic (dictionary) if answer is incorrect at end of the loop
dic[key] = 'Wrong! \'' + ans + '\' is not the capital of ' + key + ', it\'s ' + dic[key];
谢谢!
【问题讨论】:
-
random.sample() 可能对你有用。
random.sample(list(dic), 10)给你 10 个随机密钥
标签: python-3.x csv dictionary case