python - 列表索引超出范围错误 - 请求帮助

标签 python python-3.x

我试图获取 bgp_summary 字符串中每一行的第一项,并创建一个新的列表。我为此目的使用下面的代码,但出现“列表索引超出范围”错误。我相信我所指的列表索引并未超出范围,但不确定为什么会发生此错误。 如果有人可以提供帮助,我将不胜感激。

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_raw = []
bgp_peers_list_refined = []
bgp_peers_list_raw = bgp_summary.splitlines()

n=0
for n in range (len(bgp_peers_list_raw)):
    list_raw1 = []
    list_raw1 = bgp_peers_list_raw[n].split()
    bgp_peers_list_refined.append(list_raw1[0])


bgp_peers_list_refined.append(list_raw1[0])
IndexError: list index out of range

最佳答案

您的某些行是空的。如果您丢弃以下内容:

代码:

bgp_peers_list_raw = [l.strip() for l in bgp_summary.splitlines() 
                      if l.strip()]

它会工作得很好。

测试代码:

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_raw = []
bgp_peers_list_refined = []
bgp_peers_list_raw = [l.strip() for l in bgp_summary.splitlines()
                      if l.strip()]

n = 0
for n in range(len(bgp_peers_list_raw)):
    list_raw1 = []
    list_raw1 = bgp_peers_list_raw[n].split()
    bgp_peers_list_refined.append(list_raw1[0])

bgp_peers_list_refined.append(list_raw1[0])
print(bgp_peers_list_refined)

结果:

['10.0.13.213', '172.46.42.134', '172.57.13.1', '172.57.13.249',
 '172.57.13.250', '172.57.13.252', '172.57.13.252']

关于python - 列表索引超出范围错误 - 请求帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431208/

相关文章:

python - Pygame rect.center 属性

python - concurrent.futures 问题 : why only 1 worker?

python - 用 null python pandas 替换 NaN

python - 当 io.py 在同一目录中时,pandas ImportError C 扩展

Python - 根据内容值提取href值

python - 输入一个数,返回1和该数之间所有偶数的乘积

python - 如何获取字典中的其他值然后一个值等于

python - 从日志文件中提取日期?

python - pygtk关于设置按钮敏感属性的奇怪问题

python - 在递归中使用 yield 平衡内存和性能