Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Indexing - Fatal编程技术网

Python列表具有大小,但无法访问元素

Python列表具有大小,但无法访问元素,python,list,indexing,Python,List,Indexing,我构建了一些代码,从文件中剔除数据,将每行分割为三个块,并将这三个块作为列表输出: def n1gramSep(fileLine): output = [] stringBuffer = "" for char in fileLine: if char not in "!\"$.%&\'abcdefghijklmnopqrstuvwxyz01234567890": if stringBuffer != "":

我构建了一些代码,从文件中剔除数据,将每行分割为三个块,并将这三个块作为列表输出:

def n1gramSep(fileLine):
    output = []
    stringBuffer = ""

    for char in fileLine:
        if char not in "!\"$.%&\'abcdefghijklmnopqrstuvwxyz01234567890":
            if stringBuffer != "":
                output.append(stringBuffer) 
            stringBuffer = ""
        else:
            stringBuffer += char     
    return output
而且它有效!然而,在后面的一个函数中,当我尝试将列表的一些元素分配给一些变量时,我总是使indexer:list index超出范围

但这很奇怪——因为当我要求程序打印列表的内容时,我清楚地得到了我期望的结果:例如:
['9.99','dog','5.25]
。然后,当我也检查每个列表的长度时,我也得到了期望值3

然而每当我尝试
nInfo.append(n1gramInfo[x])
当x为0、1或2时,它总是失败

我完全被难住了!我有什么误解吗


谢谢。

文件中可能有一行导致了问题。例如,末尾通常有一个空行

你可以尝试这样的事情来隔离你的问题

try:
    nInfo.append(n1gramInfo[x])
except IndexError:
    print(n1gramInfo, x)
    import pdb;pdb.set_trace()  # optional, but a good time to learn the debugger

不相关:
output=filter(None,re.split(re.escape(!\“$.%&”)+“[a-z0-9]”,fileLine))
print(repr(n1gramInfo),repr(x))
就在
nInfo.append之前
J.F.Sebastian,当我在append之前添加
print(repr(n1gramInfo))
时,我会得到一个健康的列表!例如,取自CMD:
['6.483171','bridegrooms','0.78781']
和什么是
print(repr(x))
在同一个地方?这似乎是问题所在-谢谢。我应该养成更频繁地“尝试”错误语句的习惯。非常感谢。