【问题标题】:Expected output is not sorted预期输出未排序
【发布时间】:2021-10-13 11:09:42
【问题描述】:

预期输出:

{'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']})

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

【问题讨论】:

  • 想要对字典元素进行排序
  • 如果您只是想对列表进行绝对排序,请使用 sorted() kite.com/python/answers/…
  • 把最后一行改成return {k: sorted(v) for k, v in sorted(owners.items())}?
  • 仍然无法正常工作我希望 btech.txt 在开头
  • 当前输出:{'Albert': ['Input.txt', 'Output.txt', 'btech.txt'], 'Stanley': ['Code.py']} 预期输出: {'Albert': ['btech.txt', 'Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

标签: python python-3.x sorting


【解决方案1】:

编辑: 我已经意识到您希望每个数组都按字母顺序排列。要解决这个问题,您只需遍历对象上的每个键,然后使用 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))

【讨论】:

  • 这不是回答所提出的问题——这是关于结果字典中值的排序。
  • 我真的不确定你的问题。我已经用 Python3 在我的本地机器上运行了这段代码,它给了我预期的输出。请您具体说明“未排序”的含义。
  • 又看了一遍题,意思是输出没有按字母顺序排列吗?
  • 查看 OP 问题的第一行,它显示了他们想要的顺序 - 一开始我也错过了。大多数人把它放在问题的结尾处。
  • @martineau 我更新了我的回答以更好地适应这个问题。
猜你喜欢
  • 1970-01-01
  • 2017-04-26
  • 2015-11-06
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
  • 2019-03-06
  • 1970-01-01
相关资源
最近更新 更多