Python 列表索引超出 split 返回值的范围 [英] Python list index out of range on return value of split

查看:45
本文介绍了Python 列表索引超出 split 返回值的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的脚本,试图从 .txt 输入文件的第二列中提取第一个元素.

I'm writing a simple script that is trying to extract the first element from the second column of a .txt input file.

import sys

if (len(sys.argv) > 1):
    f = open(sys.argv[1], "r");
    print "file opened";

line = [];

for line in f:
    line = line.strip("\n ' '")
    line = line.split(",") 
    print line[1]

f.close();

我的输入文件如下所示:

My input file looks like this:

Client 192.168.1.13 said ``ACC: d0bb38f18da536aff7b455264eba2f1e35dd976f,389182.567,-0.042,-0.893,0.333''
Client 192.168.1.13 said ``ACC: d0bb38f18da536aff7b455264eba2f1e35dd976f,389182.590,-0.036,-0.905,0.273''
Client 192.168.1.13 said ``ACC: d0bb38f18da536aff7b455264eba2f1e35dd976f,389182.611,-0.046,-0.948,0.204''
Client 192.168.1.13 said ``ACC: d0bb38f18da536aff7b455264eba2f1e35dd976f,389182.631,-0.074,-0.978,0.170''
Client 192.168.1.13 said ``ACC: d0bb38f18da536aff7b455264eba2f1e35dd976f,389182.654,-0.100,-1.006,0.171''

我希望我的分隔符是逗号.当我打印出行的长度时,我得到了 5 个元素(如预期).但是,每当我尝试索引列表以提取数据时(即,当我调用 print line[1] 时),我不断收到以下错误:

I want my delimiter to be a comma. When I print the length of the line out, I'm getting 5 elements (as expected). However, whenever I try to index the list to extract the data (i.e., when I call print line[1]), I keep getting the following error:

file opened
Traceback (most recent call last):
  File "stats.py", line 13, in <module>
    print line[1]
IndexError: list index out of range

我不明白为什么它显然不在范围之外.

I don't understand why it's out of range when clearly it isn't.

推荐答案

我猜你的文件中有空行.如果它遍历数据然后生成异常,则空行将位于文件末尾.

I would guess you have a blank line somewhere in your file. If it runs through the data and then generates the exception the blank line will be at the end of your file.

请插入

print len(line), line

在你的

print line[1]

作为检查以验证是否是这种情况.

as a check to verify if this is the case.

您始终可以使用此构造来测试空白行,并且仅处理/打印-空白行:

You can always use this construct to test for blank lines and only process/print non-blank lines:

for line in f:
    line = line.strip()
    if line:
       # process/print line further

这篇关于Python 列表索引超出 split 返回值的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆