gpt4 book ai didi

python - 索引错误: list index out of range but I have more than enough elements?! Python

转载 作者:行者123 更新时间:2023-12-01 05:15:42 24 4
gpt4 key购买 nike

def build_country_dict(lines):
'''Return a dictionary in form of {country: count}, where country is
the country code and count is the number of medals won by athletes
from that country'''
d = {} #Start with an empty dictionary
for i in range(1, len(lines)): #For i ranging from 1 to the length of lines
line_list = lines[i].split(',') # Split lines[i] into a list - split on comma
country = line_list[6] # Get the country
if country not in d: # If the country is not in the dictionary
d[country] = 0 # Add it with count of 0
d[country] = d[country] + 1 # Add one to the country count
return d #Return the dictionary

错误IndexError:列表索引超出范围指的是line_list[6],但是我使用的列表中有11个元素,所以我不知道如何来纠正这个问题。

原始文件是一个cvs文件,所以我使用excel检查了整个文件,每一行都应该变成一个包含11个元素的列表。但是该文件太大,我无法打印所有列表。

我确实尝试过一小部分打印(行列表[6])而且打印得很好。

最佳答案

lines[i] 似乎没有足够的数据来按“,”分割。

尝试使用此代码代替country = line_list[6]

country = line_list[6] if len(line_list) > 6 else 'unknown'

或者,

try:
country = line_list[6]
except IndexError:
continue

这样更符合实际情况。

关于python - 索引错误: list index out of range but I have more than enough elements?! Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23282895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com