请求协助:解决List index out of range错误
Let's break down what's going wrong with your code and fix it step by step.
First, the root cause of your IndexError: list index out of range is likely one of two issues:
- Your
bgp_summarystring has no line breaks, sosplitlines()returns a single list element containing the entire long string. While splitting that single line works fine initially, if there are empty lines (like accidental leading/trailing newlines in your actual input),splitlines()will create empty string entries. Splitting an empty string withsplit()gives you an empty list, and trying to access index0of that empty list throws the error. - You also have redundant code where you append
list_raw1[0]twice, which would duplicate every IP in your result list (though this isn't causing the error itself).
Here's how to fix this based on what your actual input should look like:
Case 1: Your input string has no line breaks (all peers in one line)
It looks like your bgp_summary is a single line of space-separated values, where each peer's data takes exactly 9 fields (IP, ASN, and other metrics ending with Establ). We can split all fields first, then group them into chunks of 9 to extract each peer's IP:
bgp_summary = """ 10.0.13.213 65510 658 86 0 0 2d 3:43:06 Establ 172.46.42.134 65513 819 7 0 11 2d 3:50:49 Establ 172.57.13.1 65501 15427 52 0 0 0d 2:26:01 Establ 172.57.13.249 65513 13449 2517 0 0 2d 3:50:21 Establ 172.57.13.250 65513 134 2515 0 0 4d 3:50:21 Establ 172.57.13.252 65513 46 142 0 0 3:50:32 Establ """ # Split all values into a single list all_fields = bgp_summary.split() bgp_peers_list_refined = [] # Iterate in steps of 9 (since each peer has 9 fields) for i in range(0, len(all_fields), 9): # Grab the first field (the IP) from each peer's chunk bgp_peers_list_refined.append(all_fields[i]) print(bgp_peers_list_refined)
Case 2: Your input should have one peer per line (line breaks were lost)
If your original bgp_summary is supposed to have each peer on its own line (common for BGP output), we can split by lines, skip any empty lines, and extract the first field from each valid line:
bgp_summary = """10.0.13.213 65510 658 86 0 0 2d 3:43:06 Establ 172.46.42.134 65513 819 7 0 11 2d 3:50:49 Establ 172.57.13.1 65501 15427 52 0 0 0d 2:26:01 Establ 172.57.13.249 65513 13449 2517 0 0 2d 3:50:21 Establ 172.57.13.250 65513 134 2515 0 0 4d 3:50:21 Establ 172.57.13.252 65513 46 142 0 0 3:50:32 Establ""" bgp_peers_list_refined = [] for line in bgp_summary.splitlines(): # Skip empty lines to avoid splitting into an empty list stripped_line = line.strip() if not stripped_line: continue fields = stripped_line.split() # Ensure we have at least one field before accessing index 0 if fields: bgp_peers_list_refined.append(fields[0]) print(bgp_peers_list_refined)
Both solutions will give you a clean list of peer IPs without the index error.
内容的提问来源于stack exchange,提问作者DPK

