내 .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