我的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循环中终止。
发布于 2019-07-16 23:40:41
有几个原因导致了这个问题。第一个问题是,在遍历列表时,会使列表发生变化。这就是为什么它没有在列表的项目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)发布于 2019-07-16 23:42:16
您的问题是您正在从列表中删除项目,但仍在增加索引。改为执行以下操作:
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[0]) - len(push_configs[0].lstrip())
while(whitespace != 1):
print whitespace
push_configs.pop(config_index)
whitespace = len(push_configs[0]) - len(push_configs[0].lstrip())
print whitespace发布于 2019-07-17 00:55:41
我看到有两个问题:第一,你弹出并不断增加索引,第二,列表中可能没有任何元素只有一个空格。如果我误解了这个问题,请纠正我
https://stackoverflow.com/questions/57060830
复制相似问题