私の.csvファイルには合計12カ国(12カ国)がありますが、12カ国のうち10カ国をランダムに選択したいと思います。csv辞書から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];
ありがとうございます!あなたが鍵をsample
ために探している
[random.sample()](https://docs.python.org/3/library/random.html#random.sample)可能性がありますあなたのために働く。 'random.sample(list(dic)、10)'はあなたに10のランダムキーを与えます – Felk