我有以下代码可以为员工随机分配数字:
emp_numbers = {}
employees = ['empA', 'empB', 'empC', 'empD', 'empE', 'empF']
numbers = 26
for x in employees:
emp_numbers[x] = []
emp = list(emp_numbers.keys())
for number in range(1, numbers+1):
emp_name = choice(emp);
emp_numbers[emp_name].append(number)
print (emp_numbers)
输出:
{'empA': [4, 25], 'empB': [2, 10, 11, 15, 18, 20, 22, 23], 'empC': [5, 13, 21, 24], 'empD': [3, 6, 7, 8, 12, 16, 19, 26], 'empE': [14], 'EmpF': [1, 9, 17]}
效果很好。但是,我不知道如何使它尽可能均匀地分配数字。有些员工有2个数字,有些有8个。关于如何获取数字的任何建议?
谢谢!
答案 0 :(得分:0)
假设人数与员工人数平均可比,则可以这样处理:
import random
import collections
employees = ["empA", "empB", "empC", "empD", "empE", "empF"] # employee names
numbers = list(range(1, 27)) # numbers from 1..26
emp_numbers = collections.defaultdict(list) # collects the employee numbers
random.shuffle(numbers) # shuffle the numbers to distribute
for i, number in enumerate(numbers): # get the index of the number and the number
employee = employees[i % len(employees)] # round-robin over the employees...
emp_numbers[employee].append(number) # ... and associate a number with a name.
print(emp_numbers)
输出例如
{'empF': [25, 4, 9, 21], 'empD': [2, 10, 3, 11], 'empE': [18, 5, 17, 15], 'empB': [7, 24, 26, 6, 8], 'empC': [1, 14, 13, 12], 'empA': [16, 23, 20, 19, 22]}
如果数字不能被平均整除,那么某些人将获得比其他人更多的数字。
答案 1 :(得分:0)
由于您要分配所有数字,因此可以将数字的顺序随机化,而不是雇员:
numbers = list(range(1, 27))
random.shuffle(numbers)
然后,您可以使用切片为每位员工平均分配数字:
for idx, employee in enumerate(employees):
emp_numbers[employee] = numbers[idx::len(employees)]
[start::n]
语法选择从n
开始的第start
条。第一个雇员获得项目0、6、12,...,第二个雇员获得项目1、7、13,...,依此类推。
import random
# initial setup
employees = ['empA', 'empB', 'empC', 'empD', 'empE', 'empF']
numbers = list(range(1, 26+1))
# dict to hold assignment and randomly shuffled numbers
employee_numbers = {}
random.shuffle(numbers)
# assign shuffled numbers to employees
for idx, employee in enumerate(employees):
employee_numbers[employee] = numbers[idx::len(employees)]
# print result
print(employee_numbers)