简体   繁体   中英

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.
From that list I want to parse out certain values, which I am doing that with a for loop.
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')

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] . What are you splitting there?

Try this logic

  1. If it's an empty String, do nothing
  2. Split the spaces
  3. Grab the IP:Port
  4. Split off the port

Something like this

for x in out1:
    if x.strip() == '':
        continue
   ip_port = x.split()[3]
   ip = ip_port.split(':')[0]
   gnat.append(ip)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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