预期输出未排序

2024-06-26 10:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

预期产出:

{'Albert': ['btech.txt', 'Input.txt', 'Output.txt'], 'Stanley': ['Code.py']}
from collections import defaultdict

def groupAndSortOwners(files):
    owners = defaultdict(list)
    for file, owner in files.items():
        owners[owner].append(file)
    return owners

files = {
    'Input.txt': 'Albert',
    'Code.py': 'Stanley',
    'Output.txt': 'Albert',
    'btech.txt':'Albert',
}

print(groupAndSortOwners(files))

将输出获取为:

defaultdict(<class 'list'>, {'Albert': ['Input.txt', 'Output.txt', 'btech.txt'],
                             'Stanley': ['Code.py']})

请帮助我使用适当的“sort语句”以获得上述输出


Tags: pytxtinputoutputcodefileslistfile
1条回答
网友
1楼 · 发布于 2024-06-26 10:24:26

编辑: 我意识到你想要每个数组按字母顺序排列。要解决这个问题,您可以迭代对象上的每个键,然后使用sort方法对每个数组进行排序

您只需添加一个新行,在每次操作后对数组进行排序:

owners[owner] = sorted(owners[owner], key=str)

现在的完整代码是:

from collections import defaultdict

def groupAndSortOwners(files):
    owners = defaultdict(list)
    for file, owner in files.items():
        owners[owner].append(file)
        owners[owner] = sorted(owners[owner], key=str)

    return dict(owners)


files = {
    'Input.txt': 'Albert',
    'Code.py': 'Stanley',
    'Output.txt': 'Albert',
    'btech.txt':'Albert',
}

print(groupAndSortOwners(files))

旧答案

返回的对象的类型为defaultdict。您需要将defaultdict更改回标准dict。返回owners时,将对象强制转换为dict。例如:

return dict(owners)

所以整个代码现在是这样的:

from collections import defaultdict

def groupAndSortOwners(files):
    owners = defaultdict(list)
    for file, owner in files.items():
        owners[owner].append(file)
    return dict(owners)


files = {
    'Input.txt': 'Albert',
    'Code.py': 'Stanley',
    'Output.txt': 'Albert',
    'btech.txt':'Albert',
}

print(groupAndSortOwners(files))

相关问题 更多 >