首页 > 解决方案 > For 循环需要不止一次迭代才能完成

问题描述

我在 Python 中做一些事情,我遇到了一个奇怪的 for 循环行为。我试图做的是在满足某个条件时删除列表的一个元素:

for l, line in enumerate(lines):
  temp = line.split()
  if '_' not in temp[0]:
    del lines[l]

但是,当我执行此代码时,名为的列表lines仍然包含行的第一个元素上没有下划线的单词。因此,我尝试通过检查代码lines执行前后的长度来重申相同的代码:

temp1 = 1
temp2 = 0
while temp1 != temp2:
  temp1 = len(lines)
  for l, line in enumerate(lines):
    temp = line.split()
    if '_' not in temp[0]:
      del lines[l]
  temp2 = len(lines)
  print(temp1,temp2)

我在输出中得到的是确认这个 for 循环需要完成的不仅仅是一次迭代:

82024 57042
57042 44880
44880 38908
38908 36000
36000 34611
34611 33937
33937 33612
33612 33454
33454 33378
33378 33343
33343 33327
33327 33320
33320 33317
33317 33315
33315 33315

任何人都可以解释为什么?

标签: python

解决方案


一般来说,你应该永远不要改变你正在迭代的东西。您想更改代码以便创建新列表而不是删除项目。

new_temp = []
for l, line in enumerate(lines):
  temp = line.split()
  if '_' in temp[0]:
    new_temp.append(lines[l])

推荐阅读