记录一下用python3随机生成员工排班表的过程,感觉lambda表达式、高阶函数还是蛮好玩的~
涉及几个小知识点
- 从列表(list)随机选取:
random.choice(list)
- 列表(list)打乱重排:
random.shuffle(list)
- 合并多个字典(dict):
{}.update({a:b})
- 列表(list)浅拷贝:
list.copy()
- 高阶函数:
map(function, iterable, ...)
- 匿名函数:
lambda [arg1 [,arg2,.....argn]]:expression
#!/usr/bin/env python
# coding=utf-8
"""
# :author: Terry Li
# :url: https://blog.csdn.net/qq_42183962
# :copyright: © 2021-present Terry Li
# :motto: I believe that the God rewards the diligent.
"""
import random
def random_schedule_table():
"""返回一个随机生成的排班表_schedule, 类型为list"""
_schedule_times = len(days)
_schedule = {}
_chache_days = days.copy()
def choice_and_delete_day(i):
day = random.choice(_chache_days)
rtn = day
_chache_days.remove(day)
return rtn
days_fixed_length = list(map(choice_and_delete_day, range(_schedule_times)))
#随机打乱
random.shuffle(days_fixed_length)
#print(days_fixed_length)
time_fixed_length = list(map(lambda i: random.choice(times), range(_schedule_times)))
#随机打乱
random.shuffle(time_fixed_length)
#print(time_fixed_length)
day_and_time_schedule = zip(days_fixed_length, time_fixed_length)
for i in day_and_time_schedule:
_schedule.update({i[0]: i[1]})
return _schedule
if __name__ == '__main__':
"""关注这几个入参即可"""
users = ["甲", "乙", "丙"]
days = ["1号", "2号", "3号", "4号", "5号"]
times = ['早班', '晚班']
scheduling_table = {}
schedule = {}
# 生成1个装了30个随机组合的池子,然后使用者再从池子里随机选
pool_size = 30
pool = [random_schedule_table() for _ in range(pool_size)]
#print(pool)
for user in users:
sche_table = random.choice(pool)
scheduling_table.update({user: sche_table})
print(scheduling_table)
生成结果如下
{
'甲': {'1号': '晚班', '4号': '晚班', '5号': '晚班', '2号': '早班', '3号': '早班'},
'乙': {'2号': '晚班', '1号': '早班', '5号': '晚班', '4号': '晚班', '3号': '早班'},
'丙': {'5号': '早班', '2号': '晚班', '1号': '晚班', '4号': '早班', '3号': '晚班'}
}