For循环需要完成多个迭代

时间:2019-07-06 09:09:13

标签: python

我正在用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

任何人都可以解释原因吗?

1 个答案:

答案 0 :(得分:1)

通常,您应该永远不要更改要迭代的内容。您想要更改代码,以便创建新列表而不是删除项目。

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