Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
索引器:列表索引超出范围,但我有足够的元素?!python_Python - Fatal编程技术网

索引器:列表索引超出范围,但我有足够的元素?!python

索引器:列表索引超出范围,但我有足够的元素?!python,python,Python,错误索引器:列表索引超出范围指的是行列表[6],但是我使用的列表中有11个元素,因此我不知道如何更正 原始文件是一个cvs文件,所以我使用excel检查了整个过程,每一行都应该变成一个包含11个元素的列表。但是文件太大,我无法打印所有列表 我试着吃了一小部分 打印(行列表[6]) 而且它打印得很好。行[i]似乎没有足够的数据按“,”分割 请尝试此代码,而不是country=line\u list[6] def build_country_dict(lines): '''Return a

错误
索引器:列表索引超出范围
指的是
行列表[6]
,但是我使用的列表中有11个元素,因此我不知道如何更正

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

我试着吃了一小部分 打印(行列表[6])
而且它打印得很好。

行[i]
似乎没有足够的数据按“”分割

请尝试此代码,而不是
country=line\u list[6]

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
或者

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

这更适合这种情况。

您是否尝试在每次迭代中打印
行列表
,以查看在错误发生之前是否确实有足够的元素?也许你有一行奇怪的代码,甚至是一行空白,类似的。请参阅以获取提示,如何在任务中使用defaultdict(和两个替代解决方案)。此代码行替换有效。非常感谢。它最后说我有一个未知的,所以我又检查了2000多行,但仍然找不到。为什么索引从
1
开始index是从
0
开始的,很可能是
c
等等。
try:
    country = line_list[6]
except IndexError:
    continue