Help with dict and iter

andrew cooke andrew at acooke.org
Sun Mar 29 17:17:50 CEST 2009


mattia wrote:
> Hi all, I a list of jobs and each job has to be processed in a particular
> order by a list of machines.
> A simple representation is:
> # Ordering of machines
> JOB1 = [3, 1, 2, 4]
> JOB2 = [2, 3, 1, 4]
> JOBS = [JOB1, JOB2]
> NJOBS = len(JOBS)
> Now, I have a list of jobs and I want to have the associated list of
> machines, e.g:
> [JOB1, JOB1, JOB2] --> [3, 1, 2]
> My original idea was to have a dict with associated the job number and an
> iterator associated by the list of machines:
> job_machine = dict((x+1, iter(JOBS[x])) for x in range(NJOBS))
> Now, something like:
> for x in job_list:
>     print(next(job_machine[x]))
> Works good, but imagine I have a list of job_list, now obviously I have a
> StopIteration exception after the
> first list. So, I'm looking for a way to "reset" the next() value every
> time i complete the scan of a list.

don't you just want to have a new job machine?

for job_list in job_list_list:
  job_machine = dict((x+1, iter(JOBS[x])) for x in range(NJOBS))
  for x in job_list:
    print(next(job_machine[x]))

you can certainly write a generator that resets itself - i've done it by
adding a special reset exception and then using generator.throw(Reset()) -
but it's a lot more complicated and i don't think you need it.  if you do,
you need to look at writing generators explicitly using yield, and then at
"enhanced generators" for using throw().

andrew




More information about the Python-list mailing list