如何修复“列表索引超出范围”错误?

问题描述 投票:0回答:1

我有一个 csv 和 tsv 文件,我必须将其创建到字典和列表中。我必须将它们组合起来以获得特定的输出,但我不断收到此“列表索引超出范围”错误,我不确定我必须做什么。

这是我一直在使用的代码。 导入 csv

    def make_happy_dict():
        filename = 'happiness.csv'
        happy_dict = {}
        with open(filename, "r") as infile:
            infile.readline()
            happy_csv = csv.reader(infile)
            for row in happy_csv:
                happy_dict[row[0]] = row[2]
        return happy_dict

    def read_gdp_data():
        Data = []
        countries = open("world_pop_gdp.tsv", 'r')
        Lines = countries.readlines()

        happy_dict = make_happy_dict()  # Step 1

        for line in Lines:
            line = line.split("\t")
            country = line[0].strip()  # Get the country name
            line[1] = line[1].replace(",","")
            line[2] = line[2].replace('$',"")
            line[2] = line[2].replace(',',"")
            line[2] = line[2].replace('\n',"")
            happiness = happy_dict.get(country)  # Step 2
            if happiness is not None:  # Step 3
                line.append(happiness)
            Data.append(line)
        return Data

    def main():
        GDP = read_gdp_data()
        for index in GDP:
            print(index[0]+","+index[1]+","+index[2]+","+index[3])  # Step 4
    
    main()

我已经能够自己打印字典,然后成功地打印列表,但不能一起打印。

list csv dictionary
1个回答
0
投票

如果你得到“列表索引超出范围”,那是因为你试图索引列表中不存在的元素。检查列表中是否有 4 个数据索引。

© www.soinside.com 2019 - 2024. All rights reserved.