[英]IndexError: list index out of range - python for loop
I am trying to fix this error, I dont really understand it as I'm a poorly skilled network engineer.我正在尝试修复这个错误,我不太理解它,因为我是一个技术欠佳的网络工程师。
I am reading lines of show commands on a router in to a list - this is all working fine.我正在将路由器上的 show 命令行读取到列表中 - 这一切正常。
From that list I want to parse out certain values, which I am doing that with a for loop.从该列表中,我想解析出某些值,我正在使用 for 循环来执行此操作。
I'm getting the result I need at the end of it, but also an error.我在最后得到了我需要的结果,但也是一个错误。
I only want certain values from the list, which is the "3rd" IP address only, no port number etc (ie '2.122.62.193', '31.49.158.183')我只想要列表中的某些值,即“第三个”IP 地址,没有端口号等(即“2.122.62.193”、“31.49.158.183”)
out1 = ['tcp 217.33.162.162:443 172.16.0.1:443 2.122.62.193:49971
2.122.62.193:49971', 'tcp 217.33.162.162:443 172.16.0.1:443
31.49.158.183:49266 31.49.158.183:49266', '']
gnat = []
for x in out1:
y = x
z = y.split(':')[3]
w = z.split()[1]
gnat.append(w)
>>> for x in out1:
... y = x
... z = y.split(':')[3]
... w = z.split()[1]
... gnat.append(w)
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
IndexError: list index out of range
>>> print gnat
['2.122.62.193', '31.49.158.183'
It may not be the most efficient code, but this is the correct result.它可能不是最有效的代码,但这是正确的结果。
Only that I don't understand the error?只是我不明白错误?
Look at the list values, you might see your error is at ''.split(':')[3]
.查看列表值,您可能会看到错误位于
''.split(':')[3]
。 What are you splitting there?你在那里分裂什么?
Try this logic试试这个逻辑
Something like this像这样的东西
for x in out1:
if x.strip() == '':
continue
ip_port = x.split()[3]
ip = ip_port.split(':')[0]
gnat.append(ip)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.