Python使用defaultdict分组文件后如何添加排序语句得到预期输出
你需要做两处调整即可得到符合预期的输出:
- 对每个所有者名下的文件名列表按不区分大小写的字典序升序排序,匹配预期的文件名顺序
- 将返回的
defaultdict转换为普通Python字典,去掉输出中的类型前缀
修改后的完整代码如下:
from collections import defaultdict def groupAndSortOwners(files): owners = defaultdict(list) for file, owner in files.items(): owners[owner].append(file) # 对每个所有者的文件列表按不区分大小写的顺序排序 for file_list in owners.values(): file_list.sort(key=str.lower) # 转换为普通字典后返回 return dict(owners) files = { 'Input.txt': 'Albert', 'Code.py': 'Stanley', 'Output.txt': 'Albert', 'btech.txt':'Albert', } print(groupAndSortOwners(files))
运行上述代码后输出结果与预期完全一致:
{'Albert': ['btech.txt', 'Input.txt', 'Output.txt'], 'Stanley': ['Code.py']}
内容的提问来源于stack exchange,提问作者Blastjackers
相关产品推荐
相关产品推荐

