[英]for loop not accessing all of the elements in a list python
The class below is driving me crazy. 下面的课程让我发疯。 It is stuck on the for loop. 它卡在for循环中。 I'm unsure why it will not access the last element in self.job_ids. 我不确定为什么它不能访问self.job_ids中的最后一个元素。 This should be working. 这应该工作。 Any ideas why this for loop does not work inside the class but it works perfectly find outside the class? 有什么想法为什么这个for循环在类内部不起作用,但是可以在类外部找到呢?
import subprocess 导入子流程
class job_runner():
def __init__(self, user_id='staffner'):
self.job_ids = ['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '10', '100']
self.user_id = user_id
def update_running_jobs(self):
'''
() ->
Remove job ids from self.job_ids which completed
'''
# find currently running jobs
curr_running = self.find_running_jobs()
#iterate over self.job_ids and see if they are in the currently running jobs
working_ids = self.job_ids
print 'start working ids:'
print working_ids
for j_id in working_ids:
# for some reason I can not access the last id in the list
print j_id
if j_id not in curr_running:
self.job_ids.remove(j_id)
print 'job_ids'
print self.job_ids
def find_running_jobs(self):
'''
() -> list running ids
Find what job ids are still running on the high performance cluster
'''
proc = subprocess.Popen(['squeue -u %s --Format=arrayjobid'%(self.user_id)], stdout=subprocess.PIPE, shell=True)
out, err = proc.communicate()
if err == None:
out_list = out.replace('ARRAY_JOB_ID', '').replace(' ', '').split('\n')
# filter out any empty strings
out_list = filter(None, out_list)
return out_list
else:
return False
curr_jobs = job_runner()
curr_jobs.update_running_jobs()
Here's the output (as you can see 100 is never accessed): 这是输出(您可以看到从未访问过100):
start working ids:
['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '10', '100']
12054807
12054808
12054809
12054810
12054811
12054812
12054813
10
job_ids
['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '100']
You should change: 您应该更改:
working_ids = self.job_ids
to: 至:
working_ids = self.job_ids[:] # create a copy of job_ids and use it
Explanation: you're modifying the list while iterating it which causes unexpected results, changing the code you'll iterate a copy of the list. 说明:您正在迭代时修改列表,这会导致意外的结果,更改代码将迭代列表的副本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.