python - 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
任何人都可以解释为什么?
解决方案
一般来说,你应该永远不要改变你正在迭代的东西。您想更改代码以便创建新列表而不是删除项目。
new_temp = []
for l, line in enumerate(lines):
temp = line.split()
if '_' in temp[0]:
new_temp.append(lines[l])
推荐阅读
- bash - 如何使用 bash 脚本从一个 FASTA 文件中计算不同蛋白质的氨基酸频率?
- php - 使用 jQuery 将文件发送到输出屏幕
- java - AWS Lambda 上基于 GPU 的算法
- xamarin.ios - Xamarin iOS-NFC 阅读器-INFCNdefReaderSessionDelegate-DidDetect 没有被调用
- java - 选择日期
- json - 努力绑定 JSON 数据 - JQuery 数据表
- java - 预期为 BEGIN_OBJECT,但为 BEGIN_ARRAY 改造
- python - 使用 python regexp 提取 IF 多行条件
- json - 使用用户基本身份验证创建颤振 Json 登录表单
- css - Clarity Wizard - 将 CSS 选择器添加到自定义向导按钮