【问题标题】:How to read csv into a list and dictionary如何将csv读入列表和字典
【发布时间】:2020-06-30 00:57:22
【问题描述】:

我想创建一个显示国家/地区的游戏,并要求用户输入所显示国家/地区的首都。用户输入首都后,会显示另一个国家并询问首都,并重复该过程,直到用户回答了十个国家的首都。然后,在游戏结束时显示用户得分。对于用户输入正确的每个大写字母,我想奖励 5 分。

这是我到目前为止所做的

import csv
import pandas
import random

african_countries = open("african_countries.csv", "r")
rd = csv.reader(african_countries)

def main():
    setupGame()
    playGame()
def setupGame():
    global countries, capitals, correct, incorrect, used
    correct = 0
    incorrect = 0
    used = [False] * 55
    countries = setupCountriesList()
    capitals = setupCapitalsDictionary()
    print("\nCOUNTRIES AND CAPITALS QUIZ!")

def playGame():
    global correct, incorrect, used
    guess = ""
    while guess.lower() != "quit":
        idx = random.randint(0, 9) 
        while used[idx]:
            idx = random.randint(0, 9) #To generate a new idx if already used
        used[idx] = True
        allTrue = True #check to see if all used is True
        for i in range(0,55):
            if used[i] == False:
                allTrue = False
        if allTrue:
            used = [False] * 55 #To reset all used to false
        country = countries[idx]
        capital = capitals[country]
        guess = input("What is the capital of " + country.upper() + "? (enter 'quit' to end)>> ")
        if guess.lower() =="quit":
            print("THANKS FOR PLAYING...You got {0} of {1} correct.\n".format(correct, (correct + incorrect)))
            break
        elif guess.lower() == capital.lower():
            print("CORRECT! {0} is the capital of {1}".format(capital, country))
            correct += 5
        else:
            print("SORRY... The capital of {0} is {1}".format(country, capital))
            incorrect += 5
        print("YOUR SCORE: You have gotten {0} of {1} correct \n".format(correct, (correct + incorrect)))

def setupCountriesList():
    countries = []
    for row in rd:
        countries.append(row[0])
    return countries

def setupCapitalsDictionary():  
    capitals = {}
    for row in rd:
        k, v = row
        capitals[k] = v
    return capitals

main()

但是我收到了这个错误:

国家和首都测验!

Traceback (most recent call last):
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 61, in <module>
    main()
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 10, in main
    playGame()
  File "c:/Users/Gideon Markus/Desktop/Cyhermes/Week 4/Project 3/Python/trial.py", line 35, in playGame
    capital = capitals[country]
KeyError: 'The Republic of Cabo Verde'
PS C:\Users\Gideon Markus\Desktop\Cyhermes\Week 4\Project 3\Python>

【问题讨论】:

  • 首先,尝试通过打印出国家列表来调试它。这样你就知道你是否在 setupCountriesList() 中输入了正确的字符串。从那个错误来看,countrylist 不是您所期望的。
  • 对上面的一个提示,您可以直接在您的 dict 对象上调用 print()。这应该会使 KeyError 的故障排除相对简单。
  • 我认为一个问题是您正在阅读setupCountriesList()setupCapitalsDictionary() 中的csv 文件rd。该文件在第一个函数中读取后将被耗尽,并且无法在第二个函数中再次使用。
  • @ChrisCharley 这是问题之一。它打印第一个列表,但不打印字典。请问这个是怎么解决的?

标签: python csv random


【解决方案1】:

这样做为我解决了这个问题。

def setupCountriesList():
    with open(african_countries, "r") as country:
        rd = csv.reader(country)
        countries = []
        for row in rd:
            countries.append(row[0])
        return countries

def setupCapitalsDictionary():  
    with open(african_countries, "r") as capital:
        drd = csv.reader(capital)
        capitals = {}
        for row in drd:
            k, v = row
            capitals[k] = v
        return capitals

【讨论】:

  • 是的,这行得通,但是当您可以在 1 个函数而不是 2 个函数中初始化两个结构时,为什么要使用 2 个不同的函数?
  • 我真的不知道如何实现这一目标。如果您能提供帮助,我将不胜感激
【解决方案2】:

要将 2 个函数合并为 1 个,您可以尝试:

def initialize_structs(african_countries):
    countries = []
    capitals = {}
    with open(african_countries, 'r') as f:
        rd = csv.reader(f)
        for row in rd:
            countries.append(row[0])
            capitals[row[0]] = row[1]

    return capitals, countries

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 2016-10-26
    • 1970-01-01
    • 2016-02-24
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多