条件成立后,我的 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/