简体   繁体   English

python 文件阅读列表索引错误:索引超出范围

[英]python file reading list index error: index out of range

I run into an error with the following code:我遇到以下代码错误:

h = 0
num = 0
with open('file1') as f:

    for row in f.readlines():
        line = row.split()

        print(line)

        # check for new
        if int(float(line[0])) != h:
            h = int(float(line[0]))
            num += 1

OUTPUT: OUTPUT:

['3', '1', '35', '31.924847576898625', '5.128603105085375', '6.20101', '0.7821899999999999', '0.23388931803044988']
[]
Traceback (most recent call last):
  File "phase_one.py", line 45, in <module>
    if int(float(line[0])) != h:
IndexError: list index out of range

Why is it when I call print(), the actual line is printed, but also there is an empty list '[]' printed after, which is causing this error?为什么我调用 print() 时,打印了实际的行,但后面还打印了一个空列表 '[]',这是导致此错误的原因?

There are two lines in your file.您的文件中有两行。 The first line is the first row.第一行是第一行。 The second line of your file is blank.文件的第二行是空白的。 Either任何一个

  1. remove that line删除该行
  2. Or, check to see if line is empty before trying to access its first element.或者,在尝试访问其第一个元素之前检查line是否为空。 Empty lists are falsy, so you can simply do if line and int(line[0])... and short-circuiting will take care of the rest.空列表是虚假的,因此您可以简单地执行if line and int(line[0])...并且短路将处理 rest。
line = row.split()
print(line)

if line and int(line[0]) != h:
    h = int(line[0])
    num += 1
  1. Or, catch the error that is thrown.或者,捕获引发的错误。
line = row.split()
print(line)

try:
    if int(line[0]) != h:
        h = int(line[0])
        num += 1
except IndexError:
    pass

Also, you don't need to convert the string to float before converting it to int .此外,您不需要在将字符串转换为int之前将其转换为float Simply if int(line[0]):= h: should be sufficient.只需if int(line[0]):= h:就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM