Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.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 - Fatal编程技术网

Python 索引超出范围错误(来自从文件中读取的数组)

Python 索引超出范围错误(来自从文件中读取的数组),python,list,Python,List,我试图计算列表中存在多少特定字符串(在本例中为“v”)。 但当我运行代码时,它会给我索引超出范围的错误。 列表是通过line.split()方法创建的 这就是我得到的: for line in open('cube.obj','r').readlines(): rawdata = line.split()[0:] data = line.split()[1:] obj.add_last(data) if rawdata[0] == 'v': v_c

我试图计算列表中存在多少特定字符串(在本例中为“v”)。 但当我运行代码时,它会给我索引超出范围的错误。 列表是通过line.split()方法创建的

这就是我得到的:

for line in open('cube.obj','r').readlines():
    rawdata = line.split()[0:]
    data = line.split()[1:]
    obj.add_last(data)
    if rawdata[0] == 'v':
        v_count += 1
cube.obj文件如下所示:

# cube
v 0.0 0.0 0.0
v 1.0 0.0 0.0
v 1.0 0.0 1.0
v 0.0 0.0 1.0
v 0.0 1.0 1.0
v 0.0 1.0 0.0
v 1.0 1.0 0.0
v 1.0 1.0 1.0

f 1 2 3 4
f 6 7 8 5
f 2 3 8 7
f 1 4 5 6
f 3 4 5 8
f 1 2 7 6
谢谢你的帮助
谢谢

如果您得到的索引超出范围错误,那是因为您引用了一个不存在的列表条目

在您的例子中,这看起来很可能是
rawdata[0]==“v”

如果rawdata是空列表,则会导致错误。如果您的行是空字符串,则会发生这种情况

line = ''
rawdata=line.split()[0:]
rawdata
> []
rawdata[0]
> ---------------------------------------------------------------------------
> IndexError                                Traceback (most recent call last)
> <ipython-input-4-c81248904650> in <module>()
> ----> 1 rawdata[0]
> IndexError: list index out of range

您可以使用生成器表达式使用
if line.strip()
捕获空行来
求和
,这样我们就不会得到一个
索引器
为空列表编制索引:

def  counts(f,ch):
    with open(f) as in_file:
        return sum(line.split()[0] == ch for line in in_file if line.strip())
print(counts("words.txt","v"))
8

if line.strip()
只有在行不是空的情况下才会为真。

如果没有看到一些输入或回溯,就无法提供帮助如果我们知道什么是
obj
以及它的
add\u last()是什么也很好
方法应该执行此操作。此错误可能会在输入文件中的空白行中发生。OP:您是否尝试使用
集合。计数器
执行此操作?每当我删除obj.add_last()时,仍然会发生相同的错误。所以我认为是if语句引起了麻烦谢谢。文件中有一个空行。有没有什么方法可以让我忽略一个空列表并计算“v”?我已经编辑了演示如何
继续
(即跳过其余语句并转到循环中的下一步)好的,谢谢,我明白了。但“继续”方法对我的案例有效吗?我已经编辑了我的帖子,这样我就可以告诉你我想做什么。请看
continue
的工作原理,它在你的情况下会起作用。
def  counts(f,ch):
    with open(f) as in_file:
        return sum(line.split()[0] == ch for line in in_file if line.strip())
print(counts("words.txt","v"))
8