for循环不访问列表python中的所有元素

时间:2017-08-29 16:26:29

标签: python

下面的课让我发疯。它停留在for循环上。我不确定为什么它不会访问self.job_ids中的最后一个元素。这应该有效。任何想法为什么这个for循环在类中不起作用但它在类外完美地找到了?

导入子流程

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()

这是输出(你可以看到永远不会访问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']

1 个答案:

答案 0 :(得分:4)

你应该改变:

working_ids = self.job_ids

为:

working_ids = self.job_ids[:]  # create a copy of job_ids and use it

说明:您在迭代它时修改列表会导致意外结果,更改您将迭代列表的副本的代码。