多列表同类元素聚类排序:Python字典人员位置固定排序问题
问题:固定在岗人员位置的排序需求
背景与数据
我有两个字典:
spots:存储每日各岗位的名额数量(示例:第0天,岗位'a'有3个名额)names:存储每日各岗位的在岗人员名单(示例:第0天,岗位'a'的在岗人员为John、Claire和Billy)
示例代码:
import pandas as pd spots = { 0: {'a': 3, 'b': 3}, 1: {'a': 3, 'b': 3}, 2: {'a': 1}, 3: {'a': 3, 'b': 3}, 4: {'a': 4, 'b': 3}, } names = { 0: {'a': ['John', 'Claire', 'Billy'], 'b': ['Paul']}, 1: {'a': ['John', 'Billy', 'Claire']}, 2: {'a': ['Billy']}, 3: {'a': ['Claire', 'Billy'], 'b': ['Paul', 'Peter']}, 4: {'a': ['Anna', 'Claire', 'Billy'], 'b': ['Peter']}, }
需求
对names中的人员列表进行排序,尽可能让同一人员的位置固定:比如Billy每天都在岗,要排在首位;Anna仅在岗一天,要排在列表末尾。同时需要根据spots的名额数量,用空字符串''补全空缺位置。
预期输出
output = { 0: {'a': ['Billy', 'Claire', 'John'], 'b': ['Paul', '', '']}, 1: {'a': ['Billy', 'Claire', 'John'], 'b': ['', '', '']}, 2: {'a': ['Billy']}, 3: {'a': ['Billy', 'Claire'], 'b': ['Paul', 'Peter', '']}, 4: {'a': ['Billy', 'Claire', 'Anna', ''], 'b': ['Peter', '', '']}, }
我的错误实现
我写了以下代码,但输出结果不符合预期,而且逻辑比较繁琐:
def name_per_category(names): unique_names = {'a': set(), 'b': set()} for key in names: for category in names[key]: unique_names[category].update(names[key][category]) return {category: sorted(unique_names[category]) for category in unique_names} def sort_names(spots, names): output = {} sorted_names = name_per_category(names) for key in spots: output[key] = {} for category in spots[key]: sorted_list = [''] * spots[key][category] if key in names and category in names[key]: for name in names[key][category]: # Find the index for each name index = sorted_names[category].index(name) print(index, name) sorted_list[index-1] = name output[key][category] = sorted_list return output output = sort_names(spots, names)
错误输出:
{0: {'a': ['Billy', 'Claire', 'John'], 'b': ['', '', 'Paul']}, 1: {'a': ['Billy', 'Claire', 'John'], 'b': ['', '', '']}, 2: {'a': ['Billy']}, 3: {'a': ['Billy', 'Claire', ''], 'b': ['Peter', '', 'Paul']}, 4: {'a': ['Billy', 'Claire', '', 'Anna'], 'b': ['Peter', '', '']}}
提问
除了输出结果错误,我的实现逻辑也较为繁琐。请问是否有更优的思路来解决这类问题?
内容的提问来源于stack exchange,提问作者aeiou
相关产品推荐
相关产品推荐

