You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用defaultdict分组文件后如何添加排序语句得到预期输出

你需要做两处调整即可得到符合预期的输出:

  1. 对每个所有者名下的文件名列表按不区分大小写的字典序升序排序,匹配预期的文件名顺序
  2. 将返回的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 06:48:02