python - While 循环在满足条件时不会终止

标签 python while-loop

条件成立后,我的 while 循环不会终止。我正在检查列表中是否有空格。如果空格等于 1,则应从 while 循环终止。

config_index = 0
push_configs = ['  dns-server 8.8.8.8 ', ' ip dhcp pool WIRELESS', '  network 10.99.99.0 255.255.255.0', '  default-router 10.99.99.1 ', '  dns-server 8.8.8.8 ', '  ip dhcp pool HUMAN_RESOURCE ', '   network 10.88.88.0 255.255.255.0', '   default-router 10.88.88.1 ', '   dns-server 8.8.8.8 ']

whitespace = len(push_configs[config_index]) - len(push_configs[config_index].lstrip())
while(whitespace != 1):
    print whitespace
    push_configs.pop(config_index)
    config_index = config_index + 1
    whitespace = len(push_configs[config_index]) - len(push_configs[config_index].lstrip())
    print whitespace

结果

2
'  dns-server 8.8.8.8 '
2
2
'  network 10.99.99.0 255.255.255.0'
2
2
'  dns-server 8.8.8.8 '
3
3
'   network 10.88.88.0 255.255.255.0'
3
3
'   dns-server 8.8.8.8 '
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
IndexError: list index out of range
>>> push_configs
[' ip dhcp pool WIRELESS', '  default-router 10.99.99.1 ', '  ip dhcp pool HUMAN_RESOURCE ', '   default-router 10.88.88.1 ']

如您所见,它会继续遍历整个列表,直到遇到“列表索引超出范围”。给定列表 push_configs,期望的结果是在 while 循环到达第二个元素后终止。

最佳答案

有几个原因导致了此问题。第一个是你在迭代列表时改变列表。这就是为什么它没有拾取列表的第 2 项(索引 0)上的空白的原因。您增加索引并弹出第一个项目,导致项目 2 成为项目 1,然后检查现在的项目 2(之前是项目 3),它没有终止条件。

您对 config_index 也没有限制,允许它超出列表范围。

最好使用 for 循环来完成

push_configs = ['  dns-server 8.8.8.8 ', ' ip dhcp pool WIRELESS', '  network 10.99.99.0 255.255.255.0', '  default-router 10.99.99.1 ', '  dns-server 8.8.8.8 ', '  ip dhcp pool HUMAN_RESOURCE ', '   network 10.88.88.0 255.255.255.0', '   default-router 10.88.88.1 ', '   dns-server 8.8.8.8 ']
for config in push_configs:
    white_space = len(config) - len(config.lstrip())
    if white_space == 1:
        break # breaks on element 2
    # do other stuff here

    print(config, white_space)

关于python - While 循环在满足条件时不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57060830/

相关文章:

python - 为什么这个 Python 字符串的大小在 int 转换失败时会发生变化

python - SQLAlchemy bool 值为 None

python - 为什么在 python 中使用已知数组初始化函数内的参数也会更改数组的值?

java - while循环陷入无限循环

python - 从自定义应用程序读取蓝牙低功耗数据到 ble dongle (csr8510)

python - 导入我的 python googlemaps 模块后,它显示 .geocode 和 .reverse_geocode 的未解析属性

c - 程序不会终止

带有循环的php mysql查询

php - while 循环将自定义函数应用于 mysql_fetch_assoc

java - 编写一个程序,将用户的输入作为数组进行比较,并使用 while 循环将其与另一个数组进行比较以检查正确答案