2017-11-06 9 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