0

I know this might be a silly question. But on this notebook there is the following piece of code:

import random

assignments_to_add = []
for _, row in routes.iterrows():
    worker = random.choice(workers)
    workers.remove(worker)
    route_stops = stops.loc[(stops['RouteName'] == row["RouteName"]) & stops['globalid'].notnull()]
    for _, stop in route_stops.iterrows():
        assignments_to_add.append(workforce.Assignment(
            project,
            assignment_type="Inspection",
            location=stop["name"],
            status="assigned",
            worker=worker,
            assigned_date=datetime.now(),
            due_date=stop["DepartTime"],
            geometry=stop["SHAPE"]
        ))
assignments = project.assignments.batch_add(assignments_to_add)

The workers in worker = random.choice(workers) is a list. So, I cant find the way to not make it random. I want the code to pick the item of the list in order as it is on the list. How could I do this?

Thanks

MVAC
  • 118
  • 8

1 Answers1

1

You have a few options for this.

List indexing:

worker = workers[0]
del workers[0]

.pop():

worker = workers.pop(0)
# pop removes item from list and assigns to worker

next():

#convert list to iterator
w_iter = iter(workers)
# anytime you need the next worker, call the following line
worker = next(workers)

Also consider looping through workers:

for worker in workers:
    do_something()

Maybe the easiest for you:

for i, row in routes.iterrows():
    worker = workers[i]
blackbrandt
  • 2,010
  • 1
  • 15
  • 32
Ken Bassett
  • 58
  • 1
  • 7
  • How could it fit inside the code the 'looping through workers'? – MVAC Mar 16 '22 at 14:04
  • Right now you're code is looping through routes and choosing workers without replacement (can't choose the same worker more than once). You could switch that around to looping through workers and choosing routes. `for i in range(len(workers)): route = routes.iloc[i]` But it's difficult to say because I don't know the details behind your situation. It might be easier for you to change "_" to "i" in `for _, row in routes.iterrows()` and then use the "i" to index workers. Just make sure you have at least as many workers as you have routes! I'll add that to my answer. – Ken Bassett Mar 16 '22 at 14:17
  • 1
    The `worker = workers.pop(0)` did the trick! Thanks! – MVAC Mar 16 '22 at 15:31