我有一个csv和tsv文件,我必须创建成一个字典和列表。我必须把他们结合起来,以获得一个特定的输出,但我一直得到这个“列表索引超出范围”的错误,我不知道我必须做什么。
这是我一直在使用的代码。import 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()
我已经能够打印字典,然后他们自己的名单成功,但不能在一起。
1条答案
按热度按时间uubf1zoe1#
如果你得到“列表索引超出范围”,那是因为你试图索引列表中不存在的元素。检查你的列表中是否有4个数据索引。