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

标签 python

下面的类(class)快把我逼疯了。它卡在 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']

最佳答案

你应该改变:

working_ids = self.job_ids

到:

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

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

关于python - for循环不访问列表python中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944064/

相关文章:

python - 查找现有位置 n 英里的位置

python - 语音到ext转换

python - 将 nginx 和 Gunicorn 连接在一起

Python 使用 DocxTemplate 填充 docx 表

python - 从不同的源文件以编程方式诱导 IPython 笔记本输出单元

python - 为什么 "for"循环比循环体多执行一次?

python - 根据列表中每个元素的内容从列表中获取元素

Python;读取文件并找到所需的文本

Python MySQL Update 需要 10-12 秒更新约 1000 条记录

python - PYSide/PyQt Qtreewidget字体颜色