我的代码中有一个非常奇怪的错误。 我尝试创建一个代码,为我和我的团队创建随机班次,5天内有5个班次,每个人每天都应该轮班。
代码有点大,所以我会尝试只传递相关的部分,但随时可以询问更多信息,我会尽力澄清。
from random import randint
shifts = [4, 4.2, 5, 6, 7]
days_names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
workers_names = ['Itai', 'Or', 'Reut', 'Kuka', 'Aviel']
class Day(object):
#create empty shift : worker list
def __init__(self,shift,name):
self.shift_list = { x:'' for x in shift}
self.name = name
# create a list of workers that not work this day and choose
# choose a random worker in 'worker_chosen' function
def shift_arrenge(self):
self.today_workers = [x for x in workers_names if (x not in self.shift_list.values())]
for shift, worker in self.shift_list.items():
if not worker:
self.shift_list[shift] = worker_chosen(shift,self.today_workers,self.name)
print (self.shift_list)
def worker_chosen(shift,WORKERS,day_name):
worker_chosen =''
print("today_workers")
print(WORKERS)
while(WORKERS):
worker_chosen = WORKERS.pop(randint(0, len(WORKERS)-1))
print("worker chosen: "+ worker_chosen)
#check if the worker got this shift already if not update on the worker and return it
if not (workers[worker_chosen].shift_list[shift]):
workers[worker_chosen].update(shift,day_name)
break
return worker_chosen
现在错误在worker_chosen = WORKERS.pop(randint(0, len(WORKERS)-1))
行左右。
如果已经选择了工作班次并且程序选择了另一个工作者,则在下一次我的shift_arrenge
函数调用worker_chosen时。没有选择阶梯的工人错过了我的工人名单。它像流行音乐一样完全取消了他。
这是我的调试输出示例:
today_workers
['Itai', 'Or', 'Reut', 'Kuka', 'Aviel']
worker chosen: Or
worker Or didn't got choose..
worker chosen: Reut
worker Reut didn't got choose..
worker chosen: Kuka
worker Kuka got choose!
#now move to the next shift..
today_workers
['Itai', 'Aviel'] # but only kuka got choose!
答案 0 :(得分:1)
您始终从列表中删除元素。如果其中任何一个选择 not ,请将它们重新添加到列表中,或者在实际选择它们之前不要删除它们。
请注意,WORKERS
已被操作到位;列表对象本身被更改,而不是副本。如果您打算操纵副本,请先创建一个浅拷贝:
WORKERS = list(WORKERS)
或
WORKERS = WORKERS[:]
否则你的函数的调用者将看到所做的更改; self.today_workers
仍然是对同一列表的引用。