【问题标题】:How to randomly select 10 items from csv dictionary?如何从 csv 字典中随机选择 10 个项目?
【发布时间】: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


【解决方案1】:

您正在寻找sample 密钥:

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

【讨论】:

  • 非常感谢。这是正确的解决方案。我刚刚调整了'for key in ...'
  • 但是我有一个问题。当我运行程序时,输出中仍然出现 2 个大写字母(不是随机选择的大写字母)。
  • @BudDoward 您提供的代码中没有任何内容可以做到这一点。这个问题肯定出在其他地方。
  • 例如,当伦敦和巴黎不允许出现在随机大写字母中时,它将显示“伦敦、巴黎和 10 个正确或错误答案”。然后,如果我再次运行它,它将随机分配到另外 2 个大写字母,因为字典中总共有 12 个大写字母。问题必须出在我的代码的正确/错误行上。
  • @BudDoward 我认为这发生在此处未提供的代码中。如果您无法自己追踪,我建议您使用相关代码部分提出一个新问题。
猜你喜欢
  • 1970-01-01
  • 2020-04-04
  • 2016-09-06
  • 1970-01-01
  • 2016-04-14
  • 2017-03-30
  • 2015-05-25
  • 1970-01-01
  • 2010-09-23
相关资源
最近更新 更多