如何按年月拆分客户列表并每月分配500个预订名额?
问题分析
核心需求是将5000个客户邮箱分配到不同年月,每个客户仅归属一个唯一年月,且每个年月最多容纳500个客户。当前代码的问题在于未将客户分组与年月做唯一绑定,导致同一客户可能被重复分配到不同年份的同月。
解决方案
提供两种可行实现方案,可根据实际需求选择:
方案1:分组绑定式分配(快速集中分配)
将客户按500人一组拆分,直接与年月列表一一绑定,确保每组客户仅对应一个年月。适合客户数远少于总名额、希望优先填满早期年月的场景。
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] years = ['2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031', '2032'] # 替换为从txt读取的实际邮箱列表 l_lines = [f"user{i}@example.com" for i in range(5000)] def split_clients(clients, group_size=500): # 按指定大小拆分客户列表,每组最多500人 return [clients[i:i+group_size] for i in range(0, len(clients), group_size)] # 生成按年份排序的年月列表:先2024年12个月,再2025年,以此类推 month_years = [f"{m}-{y}" for y in years for m in months] # 拆分客户为500人一组 client_groups = split_clients(l_lines) # 将客户组与年月一一绑定,只取需要的年月(5000个客户对应10组) assignment = dict(zip(month_years[:len(client_groups)], client_groups)) # 按期望格式输出 for period, clients in assignment.items(): print(f"{period} = {clients}")
方案2:循环均匀分配(分散式分配)
逐个将客户分配到不同年月,循环遍历所有年月,每个年月填满500人后再切换到下一个。适合需要将客户均匀分布到各个年月的场景。
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] years = ['2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031', '2032'] # 替换为从txt读取的实际邮箱列表 l_lines = [f"user{i}@example.com" for i in range(5000)] # 初始化所有年月的客户列表为空 assignment = {f"{m}-{y}": [] for y in years for m in months} period_list = list(assignment.keys()) current_idx = 0 for client in l_lines: current_period = period_list[current_idx] # 当前年月未满500人则添加客户 if len(assignment[current_period]) < 500: assignment[current_period].append(client) else: # 切换到下一个年月 current_idx += 1 assignment[period_list[current_idx]].append(client) # 输出有客户的年月结果 for period, clients in assignment.items(): if clients: print(f"{period} = {clients}")
两种方案均能保证每个客户仅被分配到一个年月,不会出现重复分配的问题,且严格遵守每个年月最多500人的限制。
内容的提问来源于stack exchange,提问作者Pavol
相关产品推荐
相关产品推荐

