python - 遍历列表并多次删除其元素
问题描述
我在 Python 中有以下脚本,每 30 秒检查一次列表中的所有任务,当任务完成(失败、取消或完成)时,该任务将从原始任务中删除,然后再次跟踪其他任务。代码以这种方式运行良好。
问题是我不确定while循环的每次迭代是否都在创建一个新列表,因为整个过程可能需要几个小时,所以我不想在内存中创建不必要的数据。
def download():
while tasks:
for task in tasks[:]:
success = 0
file_name = task[1]
task_index = tasks.index(task)
task_state = ee.data.getTaskStatus(task[0])[0]['state']
print(task, task_state)
if task_state == FAILED:
tasks.remove(tasks[task_index])
elif task_state in [CANCEL_REQUESTED, CANCELLED]:
tasks.remove(tasks[task_index])
elif task_state == COMPLETED:
tasks.remove(tasks[task_index])
success = 1
if success == 1:
do_something()
if tasks:
time.sleep(30)
else:
print('Done!')
download()
解决方案
您的代码中没有创建新列表。但你可能想缩短一点:
def download():
while tasks:
for task in tasks[:]:
success = 0
file_name = task[1]
task_index = tasks.index(task)
task_state = ee.data.getTaskStatus(task[0])[0]['state']
print(task, task_state)
if task_state in [CANCEL_REQUESTED, CANCELLED, FAILED, COMPLETED]:
tasks.remove(tasks[task_index])
if task_state == COMPLETED:
do_something()
if tasks:
time.sleep(30)
else:
print('Done!')
download()
我认为这段代码很好用;)
推荐阅读
- xml - 如何在.net核心的节点中发布带有前缀的xml输入
- unicode - 我需要删除现有字幕文本文件中的特定 unicode
- machine-learning - how to make grid_search on fastai learner?
- node.js - 从本地客户端调用本地 API
- c++ - wxFrame with Codeblock - 第二个 wxFrame 中不可用的块
- r - 由于 igraph 包,R 中的社区检测
- pyspark - 从许多 pyspark 列(具有特定条件)到结合所有条件的一列。火花
- mysql - 当一个表没有行时加入
- xml - 使用 XSL 在特定位置添加特定元素
- sql - PostgreSQL BETWEEN 运算符的行为不同