我有以下代码:
from collections import defaultdict
db1 = {'Adam': {'Cleaning': 4, 'Tutoring': 2, 'Baking': 1},
'Betty': {'Gardening': 2, 'Tutoring': 1, 'Cleaning': 3},
'Charles': {'Plumbing': 2, 'Cleaning': 5},
'Diane': {'Laundry': 2, 'Cleaning': 4, 'Gardening': 3}}
def by_skill(db1 : {str:{str:int}}) -> [int,[str,[str]]]:
order_skills = defaultdict(lambda:defaultdict(list))
for k,v in db1.items():
for key,value in v.items():
order_skills[value][key].append(k)
dict(order_skills)
order_skills_sorted = sorted( sorted(order_skills.items()), reverse=True )
return order_skills_sorted
if __name__ == '__main__':
print(by_skill(db1))
输出:
[(5, defaultdict(<class 'list'>, {'Cleaning': ['Charles']})), (4, defaultdict(<class 'list'>, {'Cleaning': ['Adam', 'Diane']})), (3, defaultdict(<class 'list'>, {'Cleaning': ['Betty'], 'Gardening': ['Diane']})), (2, defaultdict(<class 'list'>, {'Tutoring': ['Adam'], 'Gardening': ['Betty'], 'Plumbing': ['Charles'], 'Laundry': ['Diane']})), (1, defaultdict(<class 'list'>, {'Baking': ['Adam'], 'Tutoring': ['Betty']}))]
但是我需要输出为(为了可读性而格式化,不是必需的):(按字母顺序排列)
[(5, [('Cleaning', ['Charles'])]),
(4, [('Cleaning', ['Adam', 'Diane'])]),
(3, [('Cleaning', ['Betty']), ('Gardening', ['Diane'])]),
(2, [('Gardening', ['Betty']), ('Laundry', ['Diane']),
('Plumbing', ['Charles']), ('Tutoring', ['Adam'])]),
(1, [('Baking', ['Adam']), ('Tutoring', ['Betty'])])]
我是否需要第三次调用sorted来实现这一点?
由于评分范围在1到5之间,因此您可以构建姓名列表的技能关键字典的评分关键字典,然后遍历评分以在线性时间内按技能提取姓名:
by_skill = {}
for name, skills in db1.items():
for skill, rating in skills.items():
by_skill.setdefault(rating, {}).setdefault(skill, []).append(name)
print([
(
rating,
sorted(
(skill, sorted(names)) for skill, names in by_skill.get(rating, {}).items()
)
)
for rating in range(5, 0, -1)
])
这个输出:
[(5, [('Cleaning', ['Charles'])]), (4, [('Cleaning', ['Adam', 'Diane'])]), (3, [('Cleaning', ['Betty']), ('Gardening', ['Diane'])]), (2, [('Gardening', ['Betty']), ('Laundry', ['Diane']), ('Plumbing', ['Charles']), ('Tutoring', ['Adam'])]), (1, [('Baking', ['Adam']), ('Tutoring', ['Betty'])])]