2017-11-06 8 views
0

私の.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ために探している

+0

[random.sample()](https://docs.python.org/3/library/random.html#random.sample)可能性がありますあなたのために働く。 'random.sample(list(dic)、10)'はあなたに10のランダムキーを与えます – Felk

答えて

1

for key in random.sample(dic.keys(), 10): 
+0

ありがとうございます。これは正しい解決策です。私はちょうど 'のためにキーを調整...' –

+0

しかし、私は問題があります。私がプログラムを実行すると、2つの大文字が出力上に(ランダムに選択されていない)表示されます。 –

+0

@BudDowardあなたが提供したコードの中にはそれがありません。その問題は他のどこかにあるはずです。 – glibdud

関連する問題