简体   繁体   English

如何修复“列表索引超出范围”

[英]How to fix 'list index out of range'

I have this index error: list index out of range我有这个索引错误: list index out of range

I have this problem on a VM with Security Onion installed on it.我在安装了安全洋葱的虚拟机上遇到了这个问题。 When I tried to use the code on PyCharm, it worked perfectly.当我尝试在 PyCharm 上使用代码时,它运行良好。

ip = []
mask = []

with open('program.txt') as file:
    for line in file:
        line_words = line.split()
        print(line_words[0])
        ip.append(line_words[0])
        mask.append(line_words[1])

ip = sorted(set(ip))

for i in range(len(ip)):
    x = "block any any -> " + ip[i] + " any " + mask[i]
    with open('final.txt', 'a') as file:
        file.write(x)
        file.write('\n')
        file.close()

I expect to have the output of the last print, but it goes with the error on the append line on the VM.我希望有最后一次打印的输出,但它与 VM 上的 append 行上的错误一起出现。 I don't know how to make it work on this.我不知道如何让它在这方面发挥作用。

Your error came from the line_words[1] when the text in program.txt contain only one word.program.txt中的文本仅包含一个单词时,您的错误来自line_words[1]

Check before with a len(line_words) :使用len(line_words)之前检查:

with open('program.txt') as file:
    for line in file:
        line_words = line.split()
        print(line_words[0])
        if len(line_words) >= 2:
            ip.append(line_words[0])
            mask.append(line_words[1])

Dorian already answered the if-statement solution. Dorian 已经回答了 if 语句解决方案。 Alternatively, you can handle these errors with a try/except and print any occurring errors:或者,您可以使用 try/except 处理这些错误并打印任何发生的错误:

for line in file:
    line_words = line.split()
    print(line_words[0])
    try:
        ip.append(line_words[0])
        mask.append(line_words[1])
    except:
        print("The current line does not have enough words: {}".format(line_words)

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

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